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

后端 未结 9 1785
小蘑菇
小蘑菇 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:25

    main isn't a reserved word it's just a predefined identifier (like cin, endl, npos...), so you could declare a variable called main, initialize it and then print out its value.

    Of course:

    • the warning is useful since this is quite error prone;
    • you can have a source file without the main() function (libraries).

    EDIT

    Some references:

    • main is not a reserved word (C++11):

      The function main shall not be used within a program. The linkage (3.5) of main is implementation-defined. A program that defines main as deleted or that declares main to be inline, static, or constexpr is ill-formed. The name main is not otherwise reserved. [ Example: member functions, classes and enumerations can be called main, as can entities in other namespaces. — end example ]

      C++11 - [basic.start.main] 3.6.1.3

      [2.11/3] [...] some identifiers are reserved for use by C++ implementations and standard libraries (17.6.4.3.2) and shall not be used otherwise; no diagnostic is required.

      [17.6.4.3.2/1] Certain sets of names and function signatures are always reserved to the implementation:

      • Each name that contains a double underscore __ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.
      • Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.
    • Reserved words in programming languages.

      Reserved words may not be redefined by the programmer, but predefineds can often be overridden in some capacity. This is the case of main: there are scopes in which a declaration using that identifier redefines its meaning.

提交回复
热议问题