Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When a function missing the return value, the compiler generates a warning but not an error?

Here is a c++ function:

int FuncWithoutReturn()
{
  int var = 10;
  ++var;
  // No return value here !!!
}

In MSVC, compiler generates error:

error C4716: 'FuncWithoutReturn' : must return a value.

But in XCode 5, the compiler just spits a warning:

Control reaches end of non-void function

In runtime if I am lucky, the app crashes. I know it is a stupid error but it would be good that the compiler yields an error in first place.

Just wondering anyone knows WHY XCode think it is a warning instead of an error.

like image 441
r0n9 Avatar asked Feb 19 '14 03:02

r0n9


People also ask

What does a function return when it is missing a return statement?

This rule finds non-void functions with an execution path that does not return through an explicit return statement. The return value in such a case is undefined.

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

Flowing off the end of a non-void function with no 'return' results in undefined behavior.

What is non-void function does not return a value?

A function that does not return a value is called a non-value returning function (or a void function). A void function will automatically return to the caller at the end of the function. No return statement is required. Do not put a return statement at the end of a non-value returning function.


2 Answers

You can use -Werror=return-type to make that warning and error, in my original comment I forgot that. You can see it live.

This is both an option in clang and gcc, as far as I understand XCode can use either one.

Falling off the end of value returning function is undefined behavior, we can see this by going to the draft C++ standard section 6.6.3 The return statement paragraph 2 which says:

[...]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.

Undefined Behavior does not require a diagnostic(warning or error), although in many cases compilers will provide one.

like image 107
Shafik Yaghmour Avatar answered Oct 16 '22 20:10

Shafik Yaghmour


You can enable it using -Werror=return-type

Just wondering anyone knows WHY XCode think it is a warning instead of an error.

Check your project's/target's/xcconfig's settings for "Mismatched Return Type" (aka GCC_WARN_ABOUT_RETURN_TYPE).

like image 26
justin Avatar answered Oct 16 '22 20:10

justin