'Is it Undefined behavior to not having a return statement for a non-void function in which control can never off over the end?
I am learning C++ using the books listed here. In particular, I read that flowing off the end of a non-void function is undefined behavior. Then I looked at this answer that says:
In C++ just flowing off the end of a value returning function is always undefined behavior (regardless of whether the function's result is used by the calling code). In C this causes undefined behavior only if the calling code tries to use the returned value.
But in this answer I read:
It is legal under C/C++ to not return from a function that claims to return something.
As you can see in the first quoted answer, the user says that in C++ it is always UB but the second quoted answer says that it is legal. They seem to be contradicting each other.
Which of the above quoted answer is correct in C++?
Also I have the following example in C++:
int func(int a, int b)
{
if(a > b)
{
return a;
}
else if(a < b)
{
return b;
}
}
int main()
{
int x =0, y =0;
std::cin>> x >> y;
if(x!=y)
{
func(x,y); //Question 1: IS THIS UB?
std::cout<<"max is: "<<func(x,y); //Question 2: IS THIS UB?
}
else
{
std::cout<<"both are equal"<<std::endl;
}
return 0;
}
I have 2 question from the above given code snippet which I have mentioned in the comments of the code above.
As can be seen from the code, the control can never flow over the end of the function func because a will never be equal to b inside the function since I have checked that condition in main separately.
Solution 1:[1]
The two statements are in no way contradictory.
The first statement is about what happens when control flow exits a non-void function without executing a return statement. The second statement is about what happens when control flow does not exit the function at all. Calls to functions like exit or std::terminate do not ever have control flow proceed past the point when those functions are called.
But that has nothing to do with the nature of the return value.
The behavior of the program when a non-void function runs out of stuff to do without an explicit return statement (or throw. Or co_return these days) is governed by [stmt.return]/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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nicol Bolas |
