递增 _Bool 是否已定义?
Is incrementing a _Bool defined?
C 标准将 _Bool 定义为包含 0 或 1 的无符号类型。如果 _Bool 类型的值 1 递增,据我所知,有两个选项:
- 值从 1 循环到 0
- 值增加到 2,它是非零的,因此在转换回 _Bool 时变为 1
在我的系统上的 GCC 和 Clang 上,行为似乎是后者。这是标准明确定义的吗?
来自 C 标准(6.3.1.2 布尔类型)
1 When any scalar value is converted to _Bool, the result is 0 if the
value compares equal to 0; otherwise, the result is 1.
又如6.5.3.1前缀自增自减运算符
2 The value of the operand of the prefix ++ operator is incremented.
The result is the new value of the operand after incrementation. The
expression ++E is equivalent to (E+=1).
最后是 6.5.16.2 复合作业
3 A compound assignment of the form E1 op = E2 is equivalent to the
simple assignment expression E1 = E1 op (E2), except that the lvalue
E1 is evaluated only once, and with respect to an
indeterminately-sequenced function call, the operation of a compound
assignment is a single evaluation. If E1 has an atomic type, compound
assignment is a read-modify-write operation with memory_order_seq_cst
memory order semantics.
注意那个(6.3 转化)
— The rank of _Bool shall be less than the rank of all other standard
integer types.
因此在表达式中使用类型 _Bool 将转换为具有更高级别的其他类型。
由于__Bool转换为标量可以有0或1的值,实际的增量操作等同于
__Bool x = false;
int v = x;
v = !!(v + 1);
x = v;
C 标准将 _Bool 定义为包含 0 或 1 的无符号类型。如果 _Bool 类型的值 1 递增,据我所知,有两个选项:
- 值从 1 循环到 0
- 值增加到 2,它是非零的,因此在转换回 _Bool 时变为 1
在我的系统上的 GCC 和 Clang 上,行为似乎是后者。这是标准明确定义的吗?
来自 C 标准(6.3.1.2 布尔类型)
1 When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.
又如6.5.3.1前缀自增自减运算符
2 The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation. The expression ++E is equivalent to (E+=1).
最后是 6.5.16.2 复合作业
3 A compound assignment of the form E1 op = E2 is equivalent to the simple assignment expression E1 = E1 op (E2), except that the lvalue E1 is evaluated only once, and with respect to an indeterminately-sequenced function call, the operation of a compound assignment is a single evaluation. If E1 has an atomic type, compound assignment is a read-modify-write operation with memory_order_seq_cst memory order semantics.
注意那个(6.3 转化)
— The rank of _Bool shall be less than the rank of all other standard integer types.
因此在表达式中使用类型 _Bool 将转换为具有更高级别的其他类型。
由于__Bool转换为标量可以有0或1的值,实际的增量操作等同于
__Bool x = false;
int v = x;
v = !!(v + 1);
x = v;