yohhoyの日記

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

int a = { 42, };

プログラミング言語C++でのスカラ変数の初期化/代入において、Uniform initializationと冗長な末尾カンマ(,)を組み合せた例。構文上は許容されるが、分かりにくい書き方は避けるべき。

int a = { 42, };  // OK: 値42で初期化
int b = { 42 };   // OK: (同上)
int c = 42;       // OK: (同上)

int v;
v = { 42, };  // OK: 値42を代入
v = { 42 };   // OK: (同上)
v = 42;       // OK: (同上)

C++11 5.17/p9, 8.5/p1より一部引用。

9 A braced-init-list may appear on the right-hand side of

  • an assignment to a scalar, in which case the initializer list shall have at most a single element. The meaning of x={v}, where T is the scalar type of the expression x, is that of x=T(v) except that no narrowing conversion (8.5.4) is allowed. The meaning of x={} is x=T().
  • (snip)

1 (snip)

braced-init-list:
  { initializer-list ,opt }
  { }

関連URL