简体   繁体   中英

Why does main() have no data type (such as void, int, char) before it in C, as it does in other languages?

In every C program I had seen, there will be the main() function. Unlike in other languages, such as Java and C++, it has no data type before it. In C++ and Java there will at least be a void with main(), if not some other data type.

Why does main() have no data type with it in C?

Also, in Java the constructor has no data type used with it. Is it possible to return any value if no data type is used before functions? Or by default, can they return any value?

It's user-defined: you define it in each program. If it were a library function, you wouldn't define it, because the library would define it for you.

(As an exception to this, the Unix libraries libl and liby , the support libraries for Lex and Yacc , actually define main ; the idea is that you define a bunch of functions with standard names and you get a default main that calls these functions. You can override their main , though. Apparently Windows compilers do something similar.)

main()是用户定义的函数。

Standard clearly states that it is a user defined function:

C11: 5.1.2.2.1 Program startup

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

main() is always user defined, and can be prototyped in many ways (although some will argue that point)

(edited)

main(void){/*User defined content*/} // K&R implied `int` return type
void main(void){/*User defined content*/}  //yeah, yeah, I know
int main(void){/*User defined content*/ return 0;} //commonly used 
int main(int argc, char *argv[]){/*User defined content*/ return 0;} //commonly used 

I use a C99 implementation of a C compiler. While it very explicitly notifies of any warning or error for illegal or nefarious syntax, It did not flag the following scenario:

在此处输入图片说明

So, while it is not strictly conforming , it is evidently not illegal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM