Sunday, 3 January 2016

int main vs. void main

I get many questions similar to 'What is the difference between int main and void main() ?'

Well, this is a bit conceptual. I will try to keep things as simple as possible.

As a first step, let's dissect the main function in C.

What is it ?
Don't complicate things, it's simply a function.

What's so special about it ?
Well, it is the entry point of your application. When your program is run, this init sequence is executed.

Well, if this is a function then there must be a calling function. Who calls main ?
The Operating System itself.

How does it make a call ?
Through the C Runtime.

What to do with the return ?
Well, as you may have understood, a function returns value to its calling function.

So, OS is the calling function, what should it do with a return value ?
OK, here it gets tricky. The return value in C can be either of the two values, EXIT_SUCCESS and EXIT_FAILURE. return 0; basically means a successful run of the program and returns to the OS and the value gets pushed to the call stack.

So, you have got the point, I guess, if you are returning void, that is nothing, then the program returns nothing to the OS after successful execution. So, nothing is pushed to the call stack. So, in times it may crash when it is called from a script or a makefile.

Now, you would likely to ask, which should I use ?
Of course the int main() version and return 0; at the end. Because, that's the correct signal, you are sending to OS. Any other return value indicates an error, which obviously is not the case.
Even some compiler allows void main();, this is not standard.

So, you should avoid the practice of writing void main(); in your programs.

For more details, you can check void main(void) - the Wrong Thing

Prev     Next

No comments:

Post a Comment