yohhoyの日記

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

初期化子リスト要素数不足時の初期値

プログラミング言語Cにおいて、構造体/配列型変数宣言の初期化子リスト(initializer-list)*1で要素数が足りない場合の初期値について。

  • ポインタ型の場合、ヌルポインタ(NULL) で初期化される。*2
  • 算術型の場合、(正値または符号無し)値0 で初期化される。
    • IEEE 754準拠など浮動小数点数型が負のゼロ(-0)を取りうる処理系*3では、その初期値は 値+0 となる。
  • 注意:C言語では空の初期化子リスト(T x = {};)は構文規則上ill-formedとなる。C++言語ではOK。
struct S {
  int i;
  short s;
  double d;
  void *p;
};

S s = { 0 };
// s.s == 0 && s.d == +0 && s.p == NULL

float vf[3] = { 0.0f };
// vf[1] == +0f && vf[2] == +0f

char sz[6] = "ABC";
// sz[4] == '\0' && sz[5] == '\0'

C99 6.7.8/p10, 21より引用(下線部は強調)。

10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:

  • if it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules;
  • if it is a union, the first named member is initialized (recursively) according to these rules.

21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

*1:JIS X 3010:2003における "initializer-list" の 対訳語は "初期化子並び"

*2:ヌルポインタ値の内部表現(→id:yohhoy:20120925)には依存しない。

*3:C99 5.2.4.2.2/p4: "An implementation may give zero and non-numeric values (such as infinities and NaNs) a sign or may leave them unsigned. Wherever such values are unsigned, any requirement in this International Standard to retrieve the sign shall produce an unspecified sign, and any requirement to set the sign shall be ignored."