Ok so I was messing around on Ideone and accidentally submitted this piece of code, however to my surprise it actually compiled and ran outputting a value of 0, here.
#include <iostream>
using namespace std;
const int five( )
{
const int i = 5;
}
int main() {
cout << five( ) << endl;
return 0;
}
I then tried this in Visual Studio, and on Codepad however both failed to compile because five() does not return a value, as one would expect. My question, is of course, why does this compile fine on Ideone even though the code, to my understanding is wrong and shouldn’t compile.
Plain and simply (from C++11 6.6.3 “The return statement”):
So the compiler is pretty much allowed to do whatever it wants. Clearly, a diagnostic is something I’d prefer from a compiler, but there are times when it can be difficult to diagnose (like when the return is inside conditional logic, and the ‘end’ of the function would never be reached).
Note that I get the following warning with GCC 4.6.1 (using the
Walloption):I’m not sure what options ideone passes to GCC (I imagine that
-Wallwould do the same with the 4.3.4 version that ideone uses).Some related information:
In C it’s OK for a function that is declared to return a value to not actually do so in certain circumstances; in C it only results in undefined behavior if the function’s return value is actually used. Pre-standard C didn’t always support the
voidtype, so functions that didn’t return anything were often declared to returnint, explicitly or implicitly. From C99 6.9.1/12 “Function definitions”: If the}that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.Also, as mentioned in a couple comments, flowing off the end of
main()is treated specially by C++ and C99 and later.