A function declared to return int returns nothing. Is this Undefined Behavior?
-
28-09-2019 - |
문제
This is a valid function in C++:
int f()
{
if(false)
{
return 42;
}
}
The following definition causes UB:
int x = f(); //return value used
The question: Does the following expression statement cause UB?
f();
Quote from the standard would be very much welcome. Thanks
Warning: Remarks about stylistics are irrelevant :)
해결책
C++03 §6.6.3/2:
Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
So this is an UB in a function itself.
BTW gcc gives you a nice warning pointing to this UB:
In function 'int f()':
Line 7: warning: control reaches end of non-void function
다른 팁
C++03, §6.6.3/2: "Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function."
Note that the same is not true in C.
제휴하지 않습니다 StackOverflow