声明变量时逗号分隔如何起作用

时间:2019-03-18 18:09:14

标签: c++ c gcc gcc-warning

有一次我在代码中犯了一个错误,当时我忘了用分号结束变量初始化,而用逗号代替。但是,令我惊讶的是,它从未返回错误,并且代码正常工作。

因此,我想知道这是如何工作的?我通过编写以下代码简化了代码;

uint32_t randomfunction_wret()
{
  printf("(%d:%s) - \n", __LINE__, __FILE__);
  return 6;
}

uint32_t randomfunction()
{
  printf("(%d:%s) - \n", __LINE__, __FILE__);
}

int main()
{
    uint32_t val32 = 3, randomfunction_wret(), valx = 6, randomfunction();

    printf("(%d:%s) - %u %u\n", __LINE__, __FILE__, val32, valx);

   return 0;
}

执行时返回;

(43:test.c) - 3 6

我对初始化中分离的函数没有错误感到非常震惊。但是这些功能甚至都没有被调用。

==============更新

如果我的代码如下所示,现在每个函数都被调用了;

int main()
{
    uint32_t val32;

    val32 = 3, randomfunction_wret(), randomfunction();

    printf("(%d:%s) - %u \n", __LINE__, __FILE__, val32);

   return 0;
}

输出应为

(23:test.c) - 
(29:test.c) - 
(38:test.c) - 3 

1 个答案:

答案 0 :(得分:10)

uint32_t val32 = 3, randomfunction_wret(), valx = 6, randomfunction();

等同于;

uint32_t val32 = 3;                // Defines and initializes the variable.
uint32_t randomfunction_wret();    // Re-declares the function. Nothing else is done.
uint32_t valx = 6;                 // Defines and initializes the variable.
uint32_t randomfunction();         // Re-declares the function. Nothing else is done.

已正确定义和初始化函数中使用的变量。因此,该功能可以正常工作。


顺便说一句,randomfunction()的实现没有return语句。使用它会导致不确定的行为。


更新,以响应已编辑的帖子。

由于operator precedence,该行

val32 = 3, randomfunction_wret(), randomfunction();

等效于:

(val32 = 3), randomfunction_wret(), randomfunction();

评估逗号分隔表达式的所有子表达式。因此,将调用函数randomfunction_wretrandomfunction,并丢弃它们的返回值。