Why does defining main() with no return type compile with no error?

后端 未结 2 1284
情话喂你
情话喂你 2021-01-21 08:16

I was just testing this code by compiling it with GCC (g++);

#include 

main(int argc, char **argv){

    printf(\"something\");

}
<         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-21 08:44

    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.

提交回复
热议问题