Difference between void main and int main? [duplic

2019-01-01 09:21发布

This question already has an answer here:

Does it matter which way I declare my C++ programs?

标签: c++ standards
8条回答
人间绝色
2楼-- · 2019-01-01 09:25

The difference is one is the correct way to define main, and the other is not.

And yes, it does matter. Either

int main(int argc, char** argv)

or

int main()

are the proper definition of your main per the C++ spec.

void main(int argc, char** argv)

is not and was, IIRC, a perversity that came with older Microsoft's C++ compilers.

https://isocpp.org/wiki/faq/newbie#main-returns-int

查看更多
春风洒进眼中
3楼-- · 2019-01-01 09:29

If you're going by the spec, then you should always declare main returning an int.

In reality, though, most compilers will let you get away with either one, so the real difference is if you want / need to return a value to the shell.

查看更多
情到深处是孤独
4楼-- · 2019-01-01 09:33

The point is, C programs (and C++ the same) always (should?) return a success value or error code, so they should be declared that way.

查看更多
唯独是你
5楼-- · 2019-01-01 09:43

Bjarne Stroustrup made this quite clear:

The definition void main() is not and never has been C++, nor has it even been C.

See reference.

查看更多
浅入江南
6楼-- · 2019-01-01 09:45

You should use int main. Both the C and C++ standards specify that main should return a value.

查看更多
牵手、夕阳
7楼-- · 2019-01-01 09:47

For C++, only int is allowed. For C, C99 says only int is allowed. The prior standard allowed for a void return.

In short, always int.

查看更多
登录 后发表回答