A command-line program can finish without printing anything and still need to tell the script that launched it whether the operation succeeded. That is what the integer returned by main is for. A file-copy utility might use return 0; to report success and return EXIT_FAILURE; if it cannot open the source file. Both paths can terminate the program normally.1
If the program needs no command-line arguments, you can write this in C:
int main(void)
{
return 0;
}
In this declaration, void inside the parentheses means the function takes no parameters. The int before the function name means it returns an integer. In C++ you would usually write int main() for the same thing. To read a filename from the command line, both languages support int main(int argc, char *argv[]). For these entry points returning int, both C since C99 and standard C++ let you omit the final return 0;. Reaching the closing brace has the same effect as returning zero.12
So why does the void main() in some textbooks compile? 对弈 recommends using int main for portability, which is sound advice.3 The two languages give slightly different reasons:
- C++ explicitly requires the program entry point
mainto returnint. A compiler may acceptvoid main()as an extension, so switching compilers might produce an error.2 - C lists the two portable forms above and their equivalents, then adds “or in some other implementation-defined manner”. A C implementation can document other entry-point forms. If it supports a
mainreturningvoid, the C standard leaves the exit status received by the caller unspecified when the function finishes.1
Footnotes
-
ISO/IEC JTC 1/SC 22/WG14. (2007, September 7). Programming languages — C (N1256, C99 committee draft incorporating technical corrigenda). Open Standards. §5.1.2.2.1 ¶1, entry-point forms and quotation, §5.1.2.2.3 ¶1, termination status, §7.20.4.3, exit. ↩ ↩2 ↩3
-
ISO/IEC JTC 1/SC 22/WG21. (2017, March 21). Working Draft, Standard for Programming Language C++ (N4659). C++ Working Draft. §6.6.1 ¶2, return type, ¶5, reaching the end of the function. ↩ ↩2
-
对弈. (2019, September 4). 为什么是int main()而不是void main() [Blog post]. Tencent Cloud Developer Community. Section 3 on void main. ↩