Does ~0 yield undefined behavior? C++03 section 5 paragraph 5 seems to
suggest so:
The description of unary ~ (C++03 section 5.3.1 paragraph 8):
But perhaps "one's complement" means the value that type would have with
all bits inverted, rather than the mathematical result of inverting all
bits in the binary representation. For example, on a machine with 32-bit
int, does one's complement of 0 (attempt to) have the value 2^31-1, which
can't be represented in a signed int and is thus undefined, or does it
have the value of whatever a signed int with all set bits would have (-1
on a two's complement machine)?
I used the ~0 case for simplicity; in practice, this issue might occur
when ANDing with the complement of a mask, for example n&=~0x0F to clear
the low 4 bits of n, or ~n&0x0F to find the inverted low 4 bits of n.
suggest so:
If during the evaluation of an expression, the result is not
mathematically defined or not in the range of representable values
for its type, the behavior is undefined [...]
mathematically defined or not in the range of representable values
for its type, the behavior is undefined [...]
The operand of — shall have integral or enumeration type; the
result is the one's complement of its operand. Integral promotions
are performed. The type of the result is the type of the promoted
operand. [...]
result is the one's complement of its operand. Integral promotions
are performed. The type of the result is the type of the promoted
operand. [...]
all bits inverted, rather than the mathematical result of inverting all
bits in the binary representation. For example, on a machine with 32-bit
int, does one's complement of 0 (attempt to) have the value 2^31-1, which
can't be represented in a signed int and is thus undefined, or does it
have the value of whatever a signed int with all set bits would have (-1
on a two's complement machine)?
I used the ~0 case for simplicity; in practice, this issue might occur
when ANDing with the complement of a mask, for example n&=~0x0F to clear
the low 4 bits of n, or ~n&0x0F to find the inverted low 4 bits of n.
Comment