在值返回函数中缺少 return 语句
int foo(void) {
/* do stuff */
/* no return here */
}
int main(void) {
/* Trying to use the (not) returned value causes UB */
int value = foo();
return 0;
}
当声明一个函数返回一个值时,它必须在每个可能的代码路径上执行它。一旦调用者(期望返回值)尝试使用返回值 1 ,就会发生未定义的行为。
请注意,仅当调用者尝试使用/访问函数中的值时,才会发生未定义的行为。例如,
int foo(void) {
/* do stuff */
/* no return here */
}
int main(void) {
/* The value (not) returned from foo() is unused. So, this program
* doesn't cause *undefined behaviour*. */
foo();
return 0;
}
Version >= C99
main()
函数是此规则的一个例外,因为它可以在没有 return 语句的情况下终止,因为假设的 0
返回值将在这种情况下自动使用 2 。
1 ( ISO / IEC 9899:201x ,6.9.1 / 12)
如果到达终止函数的},并且调用者使用函数调用的值,则行为是未定义的。
2 ( ISO / IEC 9899:201x ,5.1.2.2.3 / 1)
到达终止 main 函数的}返回值 0。