Tor*_*ion 2 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;
}
Run Code Online (Sandbox Code Playgroud)
执行时返回;
(43:test.c) - 3 6
Run Code Online (Sandbox Code Playgroud)
我对初始化中分离的函数没有错误感到非常震惊。但是,这些功能甚至都没有被调用。
=============更新
从我所看到的来看,现在代码是否如下所示,现在每个函数都被调用了。
int main()
{
uint32_t val32;
val32 = 3, randomfunction_wret(), randomfunction();
printf("(%d:%s) - %u \n", __LINE__, __FILE__, val32);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出将是
(23:test.c) -
(29:test.c) -
(38:test.c) - 3
Run Code Online (Sandbox Code Playgroud)
R S*_*ahu 10
线
uint32_t val32 = 3, randomfunction_wret(), valx = 6, randomfunction();
Run Code Online (Sandbox Code Playgroud)
等价于
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.
Run Code Online (Sandbox Code Playgroud)
在函数中使用的变量已正确定义和初始化。因此,该功能可以正常工作。
顺便说randomfunction()一句,的实现没有return声明。使用它会导致未定义的行为。
由于运算符的优先级,该行
val32 = 3, randomfunction_wret(), randomfunction();
Run Code Online (Sandbox Code Playgroud)
等效于:
(val32 = 3), randomfunction_wret(), randomfunction();
Run Code Online (Sandbox Code Playgroud)
评估逗号分隔表达式的所有子表达式。因此,函数randomfunction_wret和randomfunction被调用,并且它们的返回值被丢弃。