Feb 12, 2009

Why int main and not void main in C++

There is something called “startup code” (more on this soon) which is what runs first when you start your program, sets things up (e.g. initializes stack, heap, .bss etc) and then calls “main”. Now, generally this start up code expects main to return an integer value and place it onto stack. Now, if we don’t return anything (in void main’s case), it will still take something in its place, which you don’t have any control of. e.g. If this startup code expects the value to be in a certain range, it will crash if it sees something out of it. Or imagine if the caller function pops off an int from the stack but our main never put anything into it, it would screw up the stack for good. (Ever saw segfaults on a program that runs fine but crashes while exiting)

Moreover, if you are running a script that makes its basis upon such a program, a garbage value will be returned to it leading to unknown consequences.

End Note: Some would say that leaving out the type altogether and just writing “main” should be the way to go because the return type of such functions is automatically assumed to be int by the compiler. However, this is not correct because the standard does not define an intended behaviour for this and this is totally compiler dependent and hence it is not reliable.

No comments:

Down with the Dictatorship!

    "Let them hate me, so that they fear me" - Caligula 41AD