Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a return statement mandatory for C++ functions that do not return void?

Tags:

c++

My Herb Schildt book on C++ says: "... In C++, if a function is declared as returning a value, it must return a value." However, if I write a function with a non-void return type and do not return anything, the compiler issues a warning instead of an error: "Control reaches end of non-void function."

I use gcc (MinGW) and have set the -pedantic flag.

like image 525
AlwaysLearning Avatar asked May 06 '10 20:05

AlwaysLearning


People also ask

Does non-void function need return?

The analyzer has detected a non-void function with an execution path that does not return a value. Such a function results in undefined behavior. Flowing off the end of a non-void function with no 'return' results in undefined behavior.

Is return statement mandatory in C?

In a main function, the return statement and expression are optional.

Is a return statement necessary in a void function C?

A void function will automatically return to the caller at the end of the function. No return statement is required.

Is the return statement mandatory for every function?

Every function must have at least one return statement. A procedure is not required to have any return statements. The expression in a function's return statement must evaluate to a type that matches the return type in the function's declaration.


2 Answers

§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 it depends on your definition of mandatory. Do you have to? No. But if you want your program to have well-defined behavior, yes.*

*main is an exception, see §3.6.1/5. If control reaches the end of main without a return, it will have the effect of return 0;.

like image 180
GManNickG Avatar answered Oct 16 '22 16:10

GManNickG


It is mandatory--it is an undefined behavior when such function ends without returning anything (so compilers might actually implement some kind of special behaviour). However, there are some special cases.

::main is an exception, it is assumed that return 0; is at the end of its code.

Also, you don't have to return a value in a function that does not return cleanly, f.e.:

int Foo() {
    throw 42;
}
like image 11
liori Avatar answered Oct 16 '22 18:10

liori