Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Is incrementing a _Bool defined?

A _Bool is defined by the C standard to be an unsigned type containing either 0 or 1. If a value of 1 of type _Bool is incremented, there are, as far as I can see, two options:

  • The value wraps around from 1 to 0
  • The value is incremented to 2, which is nonzero, and hence is changed into 1 when converted back to a _Bool

On GCC and Clang on my system, the behaviour seems to be the latter. Is this well-defined by the standard?

like image 289
squirl Avatar asked Mar 03 '23 09:03


2 Answers

From the C Standard ( Boolean type)

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.

And for example Prefix increment and decrement operators

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).

And at last Compound assignment

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.

Pay attention to that (6.3 Conversions)

— The rank of _Bool shall be less than the rank of all other standard integer types.

So used in expressions the type _Bool is converted to other types with a greater rank.

like image 158
Vlad from Moscow Avatar answered Mar 10 '23 23:03

Vlad from Moscow

As the __Bool converted to the scalar can have value of 0 or 1, the actual increment operation is an equivalent to

__Bool x = false;
int v = x;
v = !!(v + 1);
x = v;
like image 34
0___________ Avatar answered Mar 11 '23 00:03