Document number: N2354
Submitter: Martin Sebor
Submission Date: March 18, 2019
Subject: Constraints on parameters to main


In § Program startup the standard describes the function main and outlines constraints on the values of its parameters if the program declares it to take them.

–1–   The function called at program startup is named main. …

–2–   If they are declared, the parameters to the main function shall obey the following constraints:

Additionally, in the resolution of Defect Report 478 the committee made it clear that, despite appearances to the contrary and unlike in C++, strictly conforming C programs may call or otherwise use the function main.

This gives rise to the following question: Do the constraints on the values of main's parameters apply only when the function is called initially, during program startup, or do they also apply to any subsequent calls to main made by the program itself. In other words, is the following a strictly conforming program?

      int f (void);

      int main (int argc, char *argv[])
        if (argc < 0)      // can this ever hold?
          return 0;        // can this be eliminated?

        return f ();


      int f (void)
        return main (-1, 0);   // valid?

Note that the definition of f could be far removed from the file containing the definition of main, for example in some library, and the call to f made indirectly as a result of some other call altogether.

We note that answering the question in the affirmative and applying the constraints only to the first call to main, and regarding the above as a strictly conforming program, would make many programs theoretically vulnerable to bugs since they are commonly written with the assumption of the contrary.

On the other hand, asnwering the question in the negative and making the constraints apply to all calls would give implementations the license to diagnose invalid calls to main with arguments that fail to satisfy the constraints, and also make the assumption that the function is never called with parameter values that do no satisfy the constraints. Such an assumption might result in eliminating tests for the parameter values violating those constraints such as the (argc < 0) expression in the if statement above.

This issue was prompted by a proposal for adding such an assumption to GCC. The motivation for the change was suppressing undesirable diagnostics for unrelated transformations resulting from its absence.

Suggested Change

Clarify § Program startup to explicitly state that the constraints apply not only to the initial call to main made at program startup but to all calls to the function. Specifically, add the following footnote to the section.

–2–   If they are declared, the parameters to the main function shall obey the following constraints??):

??) The same constraints apply to any subsequent calls to the main function made after program startup by the program itself.