Search code examples
cstandardsc99c11c89

Rules of main() function when running at non-startup are the same as at startup?


There are some rules for main() function in the Standard.
If the function is called by the OS,
the value of argc is non-negative,
the return value is 0 by default, etc.

On the other hand, main() can be called by other functions,
thus implying recursive execution of main().

In this case, if main() is called by another function,
is it still true that the return value is 0 by default,
or that argc has to be non-negative?


Solution

  • As already others have stated, there is no restriction about argc. These requirements are expressed in the clause 5.1.2.2.1 (Program startup) and so they only concern the arguments with which main is called initially.

    Similarily, the relaxation of the rules for the return of main are found in clause 5.1.2.2.3 (Program termination). To make that even clearer the text states that this only concerns the initial call to main. The text is

    If the return type of the `main` function is a type
    compatible with `int`, a return from the initial call
    to the `main` function is equivalent to calling the `exit`
    function with the value returned by the main
    function as its argument; reaching the `}` that terminates 
    the `main` function returns a value of `0`.
    

    The ";" within the phrase clearly implies that the conditions of the start of the phrase are still valid for the last sub-phrase.

    All of this is only valid within 5.1.2.2 (Hosted environment), so freestanding environments may invent their own rules, but which then are not covered by the C standard.