Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A function declared to return int returns nothing. Is this Undefined Behavior?

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.

like image 357
Armen Tsirunyan Avatar asked Nov 03 '10 18:11

Armen Tsirunyan


2 Answers

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
like image 167
vitaut Avatar answered Oct 21 '22 05:10

vitaut


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.

like image 23
Jerry Coffin Avatar answered Oct 21 '22 03:10

Jerry Coffin