Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "not all control paths return a value" is warning and not an error?

I was trying to answer this question. As suggested by the accepted answer, the problem with that code is that not all control paths are returning a value. I tried this code on the VC9 compiler and it gave me a warning about the same. My question is why is just a warning and not an error? Also, in case the path which doesn't return a value gets executed, what will be returned by the function (It has to return something) ? Is it just whatever is there on top of the stack or is the dreaded undefined behavior again?

like image 516
Naveen Avatar asked Nov 14 '09 17:11

Naveen


People also ask

What does not all control paths return a value mean?

The error means that if side is neither left nor right, your function will not return a value - either side is declared improperly or your enum is.

What happens if you forget the return statement in a non void function?

If control reaches the closing curly brace ( } ) of a non- void function without evaluating a return statement, using the return value of the function call is undefined behavior.


1 Answers

Failing to return a value from a function that has a non-void return type results in undefined behaviour, but is not a semantic error.

The reason for this, as far as I can determine, is largely historical.

C originally didn't have void and implicit int meant that most functions returned an int unless explicitly declared to return something else even if there was no intention to use the return value.

This means that a lot of functions returned an int but without explicitly setting a return value, but that was OK becase the callers would never use the return value for these functions.

Some functions did return a value, but used the implicit int because int was a suitable return type.

This means that pre-void code had lots of functions which nominally returned int but which could be declared to return void and lots of other functions that should return an int with no clear way to tell the difference. Enforcing return on all code paths of all non-void functions at any stage would break legacy code.

There is also the argument that some code paths in a function may be unreachable but this may not be easy to determine from a simple static analysis so why enforce an unnecessary return?

like image 128
CB Bailey Avatar answered Sep 18 '22 12:09

CB Bailey