声明变量时逗号分隔的作用
How does a comma separation function when declaring variables
有一次我在代码中犯了一个错误,当时我忘记用分号结束变量初始化,而是用逗号代替。然而,令我惊讶的是,它从未返回错误,代码运行正常。
因此我想知道这是如何工作的?我通过编写以下代码简化了我的代码;
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;
}
执行时是returns;
(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
行
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
语句。使用它会导致未定义的行为。
更新,以响应已编辑的post。
val32 = 3, randomfunction_wret(), randomfunction();
相当于:
(val32 = 3), randomfunction_wret(), randomfunction();
计算逗号分隔表达式的所有子表达式。因此,函数 randomfunction_wret
和 randomfunction
被调用,它们的 return 值被丢弃。
有一次我在代码中犯了一个错误,当时我忘记用分号结束变量初始化,而是用逗号代替。然而,令我惊讶的是,它从未返回错误,代码运行正常。
因此我想知道这是如何工作的?我通过编写以下代码简化了我的代码;
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;
}
执行时是returns;
(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
行
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
语句。使用它会导致未定义的行为。
更新,以响应已编辑的post。
val32 = 3, randomfunction_wret(), randomfunction();
相当于:
(val32 = 3), randomfunction_wret(), randomfunction();
计算逗号分隔表达式的所有子表达式。因此,函数 randomfunction_wret
和 randomfunction
被调用,它们的 return 值被丢弃。