Declare main prototype

前端 未结 5 1542
逝去的感伤
逝去的感伤 2020-11-27 08:11

Is there any reason why I never see main\'s prototype declared in C programs, ie:

int main(int argc, char* argv[]);

int main(int argc, char* argv[])
{
    r         


        
相关标签:
5条回答
  • 2020-11-27 08:50

    Declaring the prototype means that you want to call it elsewhere, which makes no sense for main() function.

    0 讨论(0)
  • 2020-11-27 08:54

    C language standard, draft n1256:

    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;9) or in some other implementation-defined manner.

    Emphasis mine.

    0 讨论(0)
  • 2020-11-27 08:58

    The original purpose of prototypes was to support forward references to functions that could be processed by single pass compilers.

    In other words, if you have something like this:

    void function_A(){
        printf( "%d", function_B( 5 ) );
    }
    
    int function_B( int x ){
        return x * 2;
    }
    

    function_B is called before it is defined. This will create problems for simple compilers. To avoid these problems, putting prototypes at the beginning of the file, ensures that the compiler knows about all the functions in the file ahead of time, so forward references are not a problem to type check.

    Since all the valid forms of the main function are known to the compiler beforehand, it is unnecessary to create a prototype, because the compiler can type check a forward reference to main() without it.

    0 讨论(0)
  • 2020-11-27 08:59

    There's no need for a prototype, since main shouldn't be called by other procedures (and in C++ calling main is actually forbidden).

    0 讨论(0)
  • 2020-11-27 09:08

    The simple reason being that the control always first go to main.Thus it is automatically located by the compiler thus giving its prototype is redundant and is of no use.

    Also we use prototype when call to a function is made prior to its definition.Thus looking at the function prototype compiler can decide whether call is legitimate or not.But in case of main we are accustomed to provide its definition along with its declaration (which is logically correct also)thus no need of prototype.

    Even when we make our c programs organized into multiple files there is no need for prototype of main.

    0 讨论(0)
提交回复
热议问题