Difference between void main and int main? [duplic

2019-01-01 09:38发布

问题:

This question already has an answer here:

  • What should main() return in C and C++? 18 answers

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

回答1:

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



回答2:

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.



回答3:

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



回答4:

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.



回答5:

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.



回答6:

In C++, main() must return int. However, C99 allows main() to have a non-int return type. Here is the excerpt from the C99 standard.

5.1.2.2.1 Program startup

The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

int main(void) { /* ... */ }

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

int main(int argc, char *argv[]) { /* ... */ }

or equivalent; or in some other implementation-defined manner.

Also note that gcc does compile void main() although practically, it does a return 0; on encountering a closing brace.



回答7:

A long time ago I found this page (void main(void)) which contained many reasons outside of the \"the standard says it is not valid\" argument. On particular operating systems/architectures it could cause the stack to become corrupted and or other nasty things to happen.



回答8:

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.



标签: c++ standards