开发者

Declare main prototype

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[])
{
    return 0;
}

Always seemed inconsistent..


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.


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


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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜