yohhoyの日記

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

auto main() -> int

C++11で導入された関数宣言でのauto+戻り値型後置(trailing-return-type)とmain関数の組み合わせについてメモ。(少なくともill-formedとは解釈されないハズ)

2014-01-06追記:C++ Standard Core Language Defect Reports, 1003. Acceptable definitions of main にてWording変更され明確にwell-formedと解釈可能となる。

auto main() -> int {}
// int main() {} と等価

前掲コードはgcc 4.7.3, 4.8.1(-std=c++11指定)、Clang 3.1(-std=c++11指定)、MSVC10, 11で正常にコンパイルされる。

C++(N3337) 3.6.1/p2, 8.3.5/p1-3, 8.4.1/p1-3より一部引用(定義を一部簡略*1 *2)。

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() { /* ... */ }
(snip)

1 In a declaration T D where D has the form
 D1 ( parameter-declaration-clause )
and the type of the contained declarator-id in the declaration T D1 is "derived-declarator-type-list T", the type of the declarator-id in D is "derived-declarator-type-list function of (parameter-declaration-clause) returning T". (snip)
2 In a declaration T D where D has the form
 D1 ( parameter-declaration-clause ) trailing-return-type
and the type of the contained declarator-id in the declaration T D1 is "derived-declarator-type-list T", T shall be the single type-specifier auto. The type of the declarator-id in D is "derived-declarator-type-list function of (parameter-declaration-clause) returning trailing-return-type". (snip)
3 A type of either form is a function type.

1 Function definitions have the form
 function-definition:
  decl-specifier-seq declarator function-body
 function-body:
  function-try-block
(snip)

2 The declarator in a function-definition shall have the form
 D1 ( parameter-declaration-clause ) trailing-return-typeopt
as described in 8.3.5. (snip)
3 [Example: a simple example of a complete function definition is

int max(int a, int b, int c) {
  int m = (a > b) ? a : b;
  return (m > c) ? m : c;
}

Here int is the decl-specifier-seq; max(int a, int b, int c) is the declarator; { /* ... */ } is the function-body. -- end example]

関連URL

*1:main関数の宣言/定義には関係しないcv-qualifier-seqref-qualifierexception-specificationattribute-specifier-seqvirt-specifier-seqを省略。

*2:function-definition定義中のdecl-specifier-seqからopt表記を削除。"The decl-specifier-seq may be omitted in constructor, destructor, and conversion function declarations only;"(9.2/p7)