Is ‘int main;’ a valid C/C++ program?

后端 未结 9 1763
小蘑菇
小蘑菇 2020-12-23 15:32

I ask because my compiler seems to think so, even though I don’t.

echo \'int main;\' | cc -x c - -Wall
echo \'int main;\' | c++ -x c++ - -Wall

9条回答
  •  臣服心动
    2020-12-23 16:05

    No, this is not a valid program.

    For C++ this was recently explicitly made ill-formed by defect report 1886: Language linkage for main() which says:

    There does not appear to be any restriction on giving main() an explicit language linkage, but it should probably be either ill-formed or conditionally-supported.

    and part of the resolution included the following change:

    A program that declares a variable main at global scope or that declares the name main with C language linkage (in any namespace) is ill-formed.

    We can find this wording in the latest C++ draft standard N4527 which is the the C++1z draft.

    The latest versions of both clang and gcc now make this an error (see it live):

    error: main cannot be declared as global variable
    int main;
    ^
    

    Before this defect report, it was undefined behavior which does not require a diagnostic. On the other hand ill-formed code requires a diagnostic, the compiler can either make this a warning or an error.

提交回复
热议问题