Reputation: 790
I was just testing this code by compiling it with GCC (g++
);
#include <stdio.h>
main(int argc, char **argv){
printf("something");
}
It seems to build and run fine with just a warning saying;
ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
Though I defined main()
with no return type and not returning any value to it.
I then decided to test the same code by compiling it with Visual C++ compiler but it efficiently threw the error:
missing type specifier - int assumed. Note: C++ does not support default-int
and the build was not successful.
I was expecting GCC to throw an error and stop compiling instead of a warning and letting it build successfully.
Why does GCC give main()
such privilege of not letting it know its return type?
Upvotes: 4
Views: 1247
Reputation: 263257
The program is ill-formed. Omitting the return type is not permitted by the C++ standard.
The reason the compiler doesn't treat it as a fatal error is historical. Prior to the 1999 standard, C did permit the return type of a function to be omitted; it would default to int
. C++ is derived from C, so early (pre-standard) versions of C++ had the same rule.
In modern C++, omitting the return type is an error. The compiler is required to diagnose such an error, but it's not required to treat it as fatal. By printing a warning, the compiler has done its job as far as the standard is concerned.
Don't ignore warnings.
Upvotes: 7
Reputation: 320461
This happens because your are using a compiler that implements some non-standard language extensions. One of them is old-style-C-like "implicit int
" rule for function declarations. So, your function declarations implies int
return type from the point of view of that specific compiler.
It should also be said that from the point of view of C++ language, the compiler is not required to refuse to compile invalid code or issue an "error". It is only required to issue a diagnostic message, any diagnostic message. That warning you saw is already a diagnostic message. The compiler gave you a warning that says "ISO C++ forbids..." - that is already a sufficient sign that your code is broken. After that it is completely irrelevant whether your code "compiled without an error" or not.
Anyway, if you configure your compiler to disable non-standard extensions (see -pedantic-errors
flag and -std
flag), the compiler will certainly refuse to compile your code.
Upvotes: 1