Question

In my book on C, the author usually formats main() like this:

main()
{
     /* Some code */
     return;
}

But sometimes, he formats main() like this:

main()
{
     /* Some code */
     return 0;
}

What's the difference? Does it matter?

Was it helpful?

Solution

C standard says that (draft n1570)

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:

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;10) or in some other implementation-defined manner.

Now, if a function has return type other than void then you have to use

return exp;

if its return type is void then you can use (not necessary)

return;  

In case of main you can use return 0; but C99 allow you to omit the return statement.

OTHER TIPS

First, main should be declared with:

int main(void)

or

int main(int argc, char *argv[]) 

The version with command arguments has some variants, like int main(int argc, char **argv)

It must return int to conform the standard. And because of that, you must return an int at the end, return 0 if the program runs normally.

Note that in C99 or above, you can omit return 0. If main is executed to the end, return 0 is implicit.

The return value indicates (un)successful completion to the environment, allowing said environment to monitor it instead of parsing printed messages. - see this question.

You should use return 0 in main, with a properly declared main function. In functions declared as void, you can just return without a value, or let it fall off the end (no return statement).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top