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.