【问题标题】:How does a comma separation function when declaring variables声明变量时逗号分隔如何起作用
【发布时间】:2019-03-18 18:09:13
【问题描述】:

当我忘记用分号结束变量初始化而是使用逗号时,我的代码中出现了错误。然而,令我惊讶的是,它从未返回错误并且代码运行正常。

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

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 

【问题讨论】:

  • 不从声明为返回的函数返回只是未定义的行为。未定义的行为实际上意味着任何事情都可能发生,包括看起来有效。
  • @alterigel 虽然这是真的,但这不是 OP 混乱的直接原因。
  • @alterigel 如果在表达式中使用该函数的返回值,这只是未定义的行为。如果没有,则没有 UB。

标签: c++ c gcc gcc-warning


【解决方案1】:

线

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 被调用并且它们的返回值被丢弃。

【讨论】:

  • 小警告 - randomfunction 暴露了未定义的行为,可能值得添加到答案中。
  • 添加了一个额外的部分来询问您是否知道这一点。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-12
  • 2019-09-12
  • 2018-05-27
  • 1970-01-01
  • 2016-03-27
  • 2019-08-19
  • 1970-01-01
相关资源
最近更新 更多