質問

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;
役に立ちましたか?

解決

This is how the ++ operator is specified. See C++11 §5.2.6[expr.post.incr]/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.

他のヒント

why is this possible?!

Undefined behaviour is just that - undefined. Anything at all could happen.

if enough memory for 137 is allocated, then why the hell test++; results in 1?

The language specification defines that behaviour.

Because you've invoked undefined behavior by casting a pointer to a different type and performing read/write on it. UB = anything can happen, including nasal demons.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top