bricklore bricklore - 1 year ago 76
C++ Question

c++ bool anomaly -- why is this possible?

I just stumbled across this: When postifix incrementing a bool twice, the integer value still is 1 instead of the expected 2. I'd like to know why this happens.

bool test = false; // results in integer 0
test++; // results in integer 1
test++; // results in integer 1

// but there still is at least one byte of memory used:
// results in integer 137
*(unsigned char*)(&test) = 137;

Answer Source

This is how the ++ operator is specified. See C++11 §5.2.6[]/1 (emphasis mine):

The value of a postfix ++ expression is the value of its operand. [Note: the value obtained is a copy of the original value —end note] The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type or a pointer to a complete object type.

The value of the operand object is modified by adding 1 to it, unless the object is of type bool, in which case it is set to true. [Note: this use is deprecated, see Annex D. —end note]

(The prefix ++ operator has similar language to allow it to be applied to a bool value.)

Modifying the bool object through a pointer or reference of a type other than bool yields undefined behavior.