Difference between ‘int main()’, ‘void main()’ and ‘main()’ function in the C programming language

Solution 1:

Like any other function, main is also a function but with a special characteristic that the program execution always start from main. So the function main needs arguments and a return type. These int and void are its return type. Void means it will not return any value, which is also allowed.
But if want to know whether the program has terminated successfully or not, we need a return value which can be zero or a non zero value. Hence the function becomes int main () and is recommended over void main ().

Next question will strike into our minds will  be –
The same thing we can do by using getch() (for void main). then why int main is suggested?? Is there any advantage of int main over void main??

Because, the standard statements are:
int main(void)
int main(int argc, char **argv)

You can also use main() simply that means same as int main()..
int main() returns an exit value to compiler and works on most compilers.
And getch() as you mentioned has nothing to do with it. It gets character input on screen or else holds screen in other words

Solution 2:

void main() { ... } is wrong. If you’re declaring main this way, stop. (Unless your code is running in a freestanding environment, in which case it could theoretically be correct.)

main() { ... } is acceptable in C89; the return type, which is not specified, defaults to int. However, this is no longer allowed in C99. Therefore…

int main() { ... } is the best way to write main if you don’t care about the program arguments. If you care about program arguments, you need to declare the argc and argv parameters too. You should always define main in this way. Omitting the return type offers no advantage in C89 and will break your code in C99.

C Thumb rule and standards followed:

1. int main() is preferred over void main(), as per standards, and most new compilers supports int main() rather than void main().
2. int main() can help to return the error code if your program fails due to some error.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s