Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is no compiler error when return statement is not present?

Unlike Java, in C/C++ following is allowed:

int* foo ()
{
  if(x)
    return p;
// what if control reaches here
}

This often causes crashes and hard to debug problems. Why standard doesn't enforce to have final return for non-void functions ? (Compilers generate error for wrong return value)

Is there any flag in gcc/msvc to enforce this ? (something like -Wunused-result)

like image 542
iammilind Avatar asked Jun 07 '11 05:06

iammilind


People also ask

What happens if a user defined function is missing the return statement?

The “missing return statement” message occurs when a method does not have a return statement. Each method that returns a value (a non-void type) must have a statement that literally returns that value so it can be called outside the method.

How do I fix missing return statement in Java?

How to resolve the error? In order to solve the missing return statement error, we simply need to add the return statement to the method just like to the one we did in case one. So, we will return the some value of the same type which we used before the name like as: public static String checkNumber( int number) {

Why does a compiler error occur?

A compile error happens when the compiler reports something wrong with your program, and does not produce a machine-language translation. You will get compile errors.


1 Answers

It is not allowed (undefined behaviour). However, the standard does not require a diagnostic in this case.

The standard doesn't require the last statement to be return because of code like this:

while (true) {
  if (condition) return 0;
}

This always returns 0, but a dumb compiler cannot see it. Note that the standard does not mandate smart compilers. A return statement after the while block would be a waste which a dumb compiler would not be able to optimise out. The standard does not want to require the programmer to write waste code just to satisfy a dumb compiler.

g++ -Wall is smart enough to emit a diagnostic on my machine.

like image 130
n. 1.8e9-where's-my-share m. Avatar answered Oct 19 '22 17:10

n. 1.8e9-where's-my-share m.