Monday 18 February 2013

Is main() user defined function or pre-defined function?????

The main function is a user implemented function whose prototype is pre -defined by compilers (known as implementations in the C standard) and used as the entry point of a C program, as per ISO/IEC 9899:TC2 Section 5.1.2.2.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 maybe used, as they are local to the function in which they are declared):

int main(int argc, char *argv[]) { /* ... */ }

or equivalent; or in some other implementation-defined manner.

The reason why it is prototyped by the compiler is simple: the compiler needs to know where to start so it can emit a proper executable that can be run. (Of course, if you are writing a library, it is perfectly fine to not have a main function - and in fact you shouldn't have one).

No comments:

Post a Comment