yohhoyの日記

技術的メモをしていきたい日記

main関数のreturn省略

プログラミング言語C/C++において、main関数のreturn文を省略した場合の振る舞いに関するメモ。

まとめ:

  • C99より前では、戻り値が未定義(undefined)とされる。*1
  • C99以降では省略可能。「return 0;」として扱う。
  • C++では省略可能。「return 0;」として扱う。

C89/C90/C95

ANSI X3.159-1989(C89), ISO/IEC 9899:1990(C90), ISO/IEC 9899:1990/Amd.1:1995(C95)。

If the main function executes a return that specifies no value, the termination status returned to the host environment is undefined.

C99/C11

C99 5.1.2.2.3/p1より引用(下線部は強調)。C11でも同一。

If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0. If the return type is not compatible with int, the termination status returned to the host environment is unspecified.

C++

C++03 3.6.1/p5より引用(下線部は強調)。C++11でも同一。

A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing

return 0;

関連URL

*1:gccはこの言語仕様に "厳格に" 従うらしい。c - GCC default main return value is not zero - Stack Overflow参照