Why is it bad to type void main() in C++ [duplicate]

与世无争的帅哥 提交于 2019-12-04 01:36:35

问题


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?


回答1:


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...




回答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.




回答3:


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.




回答4:


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.




回答5:


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 :-)



来源:https://stackoverflow.com/questions/9857048/why-is-it-bad-to-type-void-main-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!