开发者

main can't be void [duplicate]

开发者 https://www.devze.com 2023-01-18 00:54 出处:网络
This question already has answers here: Closed 12 years ago. Possible Dupli开发者_运维百科cate: does c++ standard prohibit the void main() prototype?
This question already has answers here: Closed 12 years ago.

Possible Dupli开发者_运维百科cate:

does c++ standard prohibit the void main() prototype?

Why is C++ not letting me do void main()? It's not much of a problem, but I'm still curious.


Because return type of main()(as mandated by the Standard) must be int

C++03 [Section 3.6.1 Main function]

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.


Answer from Stroustrup himself:

Can I write "void main()"? The definition

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

is not and never has been C++, nor has it even been C. See the ISO C++ standard 3.6.1[2] or the ISO C standard 5.1.2.2.1. A conforming implementation accepts

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

and

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

A conforming implementation may provide more versions of main(), but they must all have return type int. The int returned by main() is a way for a program to return a value to "the system" that invokes it. On systems that doesn't provide such a facility the return value is ignored, but that doesn't make "void main()" legal C++ or legal C. Even if your compiler accepts "void main()" avoid it, or risk being considered ignorant by C and C++ programmers.

In C++, main() need not contain an explicit return statement. In that case, the value returned is 0, meaning successful execution. For example:

#include<iostream>

int main()
{
    std::cout << "This program returns the integer value 0\n";
}

Note also that neither ISO C++ nor C99 allows you to leave the type out of a declaration. That is, in contrast to C89 and ARM C++ ,"int" is not assumed where a type is missing in a declaration. Consequently:

#include<iostream>

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

is an error because the return type of main() is missing.

Source: http://www2.research.att.com/~bs/bs_faq2.html#void-main


Because the standard says that it returns int.


Some operating systems expect an integral return value from processes. Declare main to return an int. If you don't care about the value, simply return 0.

From the comp.lang.c FAQ:

  • "What's the correct declaration of main?" (There are two: no args, and argc/argv.)
  • Can I declare main as void, to shut off these annoying ``main returns no value'' messages? (Short answer: No)
0

精彩评论

暂无评论...
验证码 换一张
取 消