Why doesn't the definition of main () without a return type compile without errors?

I just tested this code by compiling it with GCC ( g++

);

#include <stdio.h>

main(int argc, char **argv){

    printf("something");

}

      

It seems to build and work fine, just by warning:

ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]

      

Although I have defined main()

no return type and have not returned any value to it.
Then I decided to test the same code by compiling it with the Visual C ++ compiler, but it effectively threw the error:

missing type specifier - int assumed. Note: C++ does not support default-int

      

and the build was not successful.

I expected GCC to throw an error and stop compiling instead of warning and let it fire successfully.

Why is GCC main()

so privileged that it doesn't know its return type?

+3


source to share


2 answers


The program is poorly formed. Omitting the return type is not allowed by the C ++ standard.

The reason the compiler does not treat it as a fatal error is historical. Prior to the 1999 standard, C allowed the return type of a function to be omitted; it will be by default int

. C ++ is derived from C, so early (pre-standard) versions of C ++ had the same rule.



In modern C ++, throwing a return type is a bug. The compiler should diagnose such an error, but it should not be considered fatal. By printing out a warning, the compiler has done its job as far as the standard is concerned.

Don't ignore warnings.

+5


source


This is because you are using a compiler that implements some non-standard language extensions. One is the implicit rule int

for the old-style style. Thus, your function declarations imply a return type int

from the point of view of that particular compiler.

It should also be said that from the point of view of the C ++ language, the compiler is not obliged to refuse to compile invalid code or throw an "error". Only a diagnostic message is required, any diagnostic message. This warning you saw is already a diagnostic message. The compiler gave you a warning stating that "ISO C ++ forbids ..." is already a sufficient indication of a violation of your code. After that, it doesn't matter at all whether your code will "compile without errors" or not.



In any case, if you've configured the compiler to disable non-standard extensions (see flag -pedantic-errors

and flag -std

), the compiler will certainly refuse to compile your code.

+1


source







All Articles