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

StackOverflow https://stackoverflow.com/questions/23272305

  •  09-07-2023
  •  | 
  •  

Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

main() is a user-defined function.

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:

enter image description here

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top