4

Possible Duplicate:
Difference between void main and int main?

Why is

void main() {
    //return void
}

bad?

The other day I typed this and someone pointed out to me that it is wrong to do so. I was so confused. I have been writing like this for a while now, I know it isn't C++ standard, but the compiler doesn't give out any warnings. Why is this wrong?

Community
  • 1
  • 1
Eve
  • 193
  • 1
  • 6

5 Answers5

5

Because the compiler you use does not error out on it, it doesn't mean other compilers won't. You know its not standard, after all...

K-ballo
  • 80,396
  • 20
  • 159
  • 169
4

It is wrong exactly because it is not standard. One compiler might accept this, another might complain, and the pedantic believers will burn your ass on the stake anyways.

Xeo
  • 129,499
  • 52
  • 291
  • 397
2

Because every program should indicate to other programs whether or not it completed successfully, or if there was some sort of error, and you can't do that if your main doesn't return anything.

Plus, the standard says that main should return an int.

prelic
  • 4,450
  • 4
  • 36
  • 46
2

It's wrong because the standard (at least C++03) states that main should return an int (for hosted environments, that is - freestanding environments like embedded systems can pretty well do whatever they want). From 3.6.1 Main function, paragraph 2:

An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined.

All implementations shall allow both of the following definitions of main: int main() { /* ... */ } and int main(int argc, char* argv[]) { /* ... */ }.

If you value portability at all (and you should), you should writ code that conforms with the standard as much as practicable.

Undefined behaviour like:

x = x++ + --x;

may work (for whatever definition of "work" you have) under some circumstances as well, that doesn't make it a good idea :-)

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

It's nonstandard.

i.e. you're not writing "C++" (as it was conceived) when you write this. It might look like C++, but you're not following the rules, so you're not actually writing C++.

Also its result is undefined in most cases.

Unlike in other languages like C++ or C#, where "bad" behavior causes errors, C++ allows anything to happen when an erroneous construct is used. So you can't depend on the compiler doing the "correct" thing, because it may do so one time, but not another.

In general, you want to avoid undefined behavior, so you shouldn't do this.

user541686
  • 205,094
  • 128
  • 528
  • 886