Is there any standard rules when we write the main function. I always thought the main function should always be written as

int main(int argc, char* argv)
{
     .....
     return 1;
}

But to my surprise, all these definitions are also correct . I got a compile time warning. But no compiler error or run time error. I am using gcc compiler

char * main()
{

}

char * main(int, char)
{

}

char * main(char)
{

}

Can anyone shed some light over this ?

Recommended Answers

All 3 Replies

Sure. Read this.

I've toyed around with that some time ago too, trying to see what happens when main is declared to return char*. My compiler just returned the address of the string, which is an integer.

Similar with void main() . In this case the compiler produced code to return whatever value was already contained in the ax register, an integer in C language (assuming Intel-based processor PC such as . MS-Windows and *nix).

So regardless of how you declare main() the compiler will produce the code necessary to return an integer or the compiler may just produce an error and not generate any code at all.

>Is there any standard rules when we write the main function.
Oddly enough, there are. You have two 100% portable definitions of main:

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

Equivalent types are allowed, such as char ** for argv, or a typedef. If the compiler supports something else, you can use it, but at a loss of portability. The third parameter is a common one:

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

Returning void is another common extension:

void main ( void )
{
  /* ... */
}

There are three portable return values (four if you count the C99 standard): 0 for success, EXIT_SUCCESS from <stdlib.h>, and EXIT_FAILURE from <stdlib.h>. In C99 you can also omit the return statement and 0 will be returned automatically.

>But to my surprise, all these definitions are also correct .
For a rather loose definition of "correct". One learns quickly that in C, correct is not synonymous with "compiles with a warning or two".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.