Declare main prototype

2019-01-05 06:02发布

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..

4条回答
倾城 Initia
2楼-- · 2019-01-05 06:37

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

查看更多
来,给爷笑一个
3楼-- · 2019-01-05 06:37

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.

查看更多
放荡不羁爱自由
4楼-- · 2019-01-05 06:40

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.

查看更多
Deceive 欺骗
5楼-- · 2019-01-05 06:55

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

查看更多
登录 后发表回答