Posts Tagged ‘main’

int main() vs void main()

Tuesday, October 14th, 2008

Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email

What would be the best way to start a blog that talks about building safer code? Yes, it would be to talk about the first thing you think when you start coding. The “main” function (as seen in C/C++).

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? ;) ).
(more…)

© Safer Code | int main() vs void main()

Liked this post? Get FREE Updates
Subscribe to RSS feed

Or
Enter Your E-mail ID below