Edited at

void main()をめぐるどうでもいい話

More than 3 years have passed since last update.

C言語またはC++言語で下記ソースコードを見たときに、「void main()だ!○○せ!!」とマサカリを投げるその前に。

void main()

{
/*...*/
}

注意:実用上は素直にmain関数の戻り値型をintとしましょう。通常は、main関数を下記2パターンのいずれかとします。



  • int main(void) (C++ならint main()でも同義)

  • int main(int argc, char *argv[])


language lawyer?

毎回マサカリ投擲戦争が勃発するリスクをとってでも、重箱の隅を爪楊枝でほじくりだすような議論をお好みなら、「言語仕様上、void main()はC99以降ではOK、C++ではNG」となります。


ISO/IEC 9899:1999(C99)


5.1.2.2.1 Program startup

1 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 ; 9) or in some other implementation-defined manner.

脚注9) Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as char ** argv, and so on.


最後の"; or in some other implementation-defined manner"により、main関数には処理系定義の任意の戻り値型と引数型を許容する。


ANSI X3.159-1989(C89)


2.1.2.2 Hosted environment

A hosted environment need not be provided, but shall conform to the following specifications if present.

"Program startup"

The function called at program startup is named main. The implementation declares no prototype for this function. It can be defined 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[]) { /*...*/ }

If they are defined, the parameters to the main function shall obey the following constraints:

...


C99では明記されている、処理系定義の戻り値型や引数型は許容されない。


ISO/IEC 14882:2003(C++)


3.6.1 Main function

2 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. All implementations shall allow both of the following definitions of main:

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

and

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

...


main関数の戻り値型は必ずintでなければならない。ただし、関数の型(つまり戻り値型を除く引数型)については処理系定義の型を許容する。


だからなに?

という疑問がわいたなら、おめでとうございます。main関数の戻り値型には絶対にintと書いてください。

私もそう書きます。