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; }
该main()函数是该规则的一个例外,因为它可以在没有return语句的情况下终止,因为0在这种情况下将自动使用假定的返回值2。
1(ISO / IEC 9899:201x,6.9.1 / 12)
如果到达终止函数的},并且调用者使用了函数调用的值,则该行为未定义。
2(ISO / IEC 9899:201x,5.1.2.2.3 / 1)
到达终止主函数的}会返回值0。