yohhoyの日記

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

sizeof演算子とオペランドの評価

プログラミング言語C/C++言語では、sizeof演算子オペランドは評価されない(evaluated)。

int    a = 42;
size_t n = sizeof(++a);  // 式(++a)は評価されない
assert(a == 42);

C++11

JTC1/SC22/WG21 N3337 5/p7, 5.3.3/p1より部分引用。

In some contexts, unevaluated operands appear (5.2.8, 5.3.3, 5.3.7, 7.1.6.2). An unevaluated operand is not evaluated.

The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is an unevaluated operand (Clause 5), or a parenthesized type-id.

C99

JTC1/SC22/WG14 N1256 6.5.3.4/p2より引用。

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

C99で追加された可変長配列(variable length array)に対応するため、「可変長配列型以外のときオペランドは評価されない」と定義されている。


関連URL