On 4 Nov., 11:39, hector...@gmail.com wrote:
Why doesn't my compiler (g++) flag something like this as an error:
int main()
{
}
As others have told you, main is special. It is not required to have
an explicit return, and if it returns via the end, this corresponds to
return 0. Don't ask me why that silly rule was implemented.
Now, take another function:
int foo() {}
Surprisingly this function is also ok: you just can't call it:
execution of f will lead to undefined behaviour. Why is this so?
Because it can be very difficult if not impossible to determine if a
function returns anything or not. Let's expand foo a little:
external void report_error(char const*);
int foo()
{
if (rand() < 10)
return 777;
report_error("Illegal random result in foo");
}
Now, this function might or not return, depending on report_error.
report_error might call exit, it might throw en exception or it might
just log the error and return. It might even do one of the three
things depending on some external state.
It is only when report_error returns, we get undefined behaviour.
Now, you could burden the programmer and require him to write a dummy
return-statement, but this might have its own problems: it adds dead
code to the function, and this can be a burden in some environments,
especially if the stuff returned is something more complicated than a
simple int and it might make code somewhat obfuscated (imagine the
call being replaced by a throw).
That said - if you've followed me so far - every decent compiler will
(or can be made to) warn about the missing return statement, and most
compilers also have the ability to treat certain warnings as errors,
so basically it is a question of setting your environment up in a way
that satisfies your requirements.
/Peter