Search code examples
cheader-filesprogram-entry-point

void main() { } works perfectly without a header file. How can this happen ,where is the definition of main function written in C?


I wrote the following code:

void main() {

}

How can it run without any header files?


Solution

  • From the C Standard (5.1.2.2.1 Program startup)

    1 The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

    int main(void) { /* ... */ }
    

    or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

    int main(int argc, char *argv[]) { /* ... */ }
    

    or equivalent;10) or in some other implementation-defined manner.

    Though some compilers as for example the compiler of MS VS support the declaration of the function main with the return type void nevertheless such a declaration is not a C standard declaration of the function main.

    So as the implementation declares no prototype of the function main and if the function main does not call any other function then neither header is required.

    You may just write

    int main( void )
    {
    }
    

    The return statement also may be omitted.

    Pay attention to that it is the user who defines the function main. So in the presented program above there is a definition of the function main that does not contain any statement inside its body. The function does nothing and at once returns the control to the hosted environment.