Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if I don't put a return value to a function whose prototype returns a value [duplicate]

I have just spend 3 hours, probably more, trying to find a bug, segfault or bad_allow, depending on the way I modified the code so as to understand what object was messing with the stack or memory: I put all my objects in doubt... I slaughtered classes... ( nonetheless this turned out to be good since those classes revealed themselves useless in the end :-) )...

But, indeed, the real mistake was simply: I hadn't written a return statement in a function that should return a value (in my case I needed to return a std::vector<boost::any>).

I thought that gcc (4.6.3) couldn't have compiled without it. And I feel even stranger remembering that something similar has happened to me with ms visual 2010.

So now I am wondering whether it is legal not to write a return statement ?? What happens in such cases ?

Is it related with the fact that the main that can have a return value or not ? Or should I consider going to gcc 4.7 ?

like image 782
Stephane Rolland Avatar asked Feb 24 '13 23:02

Stephane Rolland


1 Answers

It's undefined behaviour:

[C++11: 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.

It compiles because:

  1. the compiler is not required to diagnose it;
  2. diagnosing this is not always trivial, so your compiler doesn't bother;
  3. C++ is a "do it yourself" language.
like image 150
Lightness Races in Orbit Avatar answered Sep 28 '22 02:09

Lightness Races in Orbit