Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the standard let functions that don't return compile?

Tags:

c

c99

f() does not return even though it's signature say it should. Why is the reason for allowing this to compiling? Is there a reason the C standard does not require the compiler to make it fail?

I know that it is Undefined behavior and all, but why is it allowed in the first place? Is there a historical reason?

double f(){}

int main()
{
    f();
    return 0;
}
like image 953
nishantjr Avatar asked Jan 23 '13 15:01

nishantjr


People also ask

What does a function return if it has no return statement in it C++?

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.

Do all functions need a return C++?

tl;dr: C++ functions do not require a return keyword in them to be well-formed and compile, though it will likely cause undefined behaviour. Your specific compiler may also warn or error.

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

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.


1 Answers

Is there a reason the C standard does not require the compiler to make it fail?

By invoking undefined behavior, the C standard allowed the compilers to be less complicated. There is indeed some cases, such as if statements, in which it is hard to say whether the function returns a value or not:

int f(int n)
{
  if (n > 0) return 1;
}
  • If I write f(5), it is easy for the compiler to say that the function is correct.
  • If I write f(-5), it is also easy to detect an undefined return value.

But if the argument comes from user input for example, how should the compiler be able to know whether the function returns a value? Since this could both a valid or a wrong program, C standard allows the compilers to do what they want. C is designed to be as smart and simple as possible.

like image 69
md5 Avatar answered Sep 18 '22 05:09

md5