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

醉酒当歌 提交于 2019-12-01 06:22:33

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

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.

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.

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.

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

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