int main() And void main() - Differeance!

We’ve been brought up with many different variations of this popular function. Some books/teachers like to write it as “int main”, some write it as “void main” and then there are some who make do with just “main”, forgoing the return type altogether. So, which one out of them is correct? Or does it even make a difference?

The answer to the 2nd question is “YES”. It makes a whole world of difference as in it could:
» do nothing
» or give you a compile time warning
» or crash the program
» or cause problems in your invocation environment

Now, we go back to the first question. Which is the correct form and why?
The answer is “int main” is the correct type for C++.
But for C, it is a bit tricky and I’d say “int main” is the recommended way.
The simple reasoning is “because the C and C++ standards say so”. (See this however, which is what is leads to a bit of confusion though and makes it implementation dependent in c)

But lets take a brief look at the practical reasons for this because you might wonder “My compiler doesn’t give me a warning for void main, so why should I care?” (If your compiler does that, then its time to switch to something else. Did I hear you are using a Microsoft compiler? ).

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.

Please post your comments about this article or if there is something that I missed out on. Also let us know if there is something in particular that you’d want us to talk about.

© Safer Code

0 comments:

Blog Widget by LinkWithin