clanguage-lawyerbitwise-operatorsones-complement

Can bitwise operators have undefined behavior?


Bitwise operators (~, &, | and ^) operate on the bitwise representation of their promoted operands. Can such operations cause undefined behavior?

For example, the ~ operator is defined this way in the C Standard:

6.5.3.3 Unary arithmetic operators

The result of the ~ operator is the bitwise complement of its (promoted) operand (that is, each bit in the result is set if and only if the corresponding bit in the converted operand is not set). The integer promotions are performed on the operand, and the result has the promoted type. If the promoted type is an unsigned type, the expression ~E is equivalent to the maximum value representable in that type minus E.

On all architectures, ~0 produces a bit pattern with the sign bit set to 1 and all value bits set to 1. On a one's complement architecture, this representation correspond to a negative zero. Can this bit pattern be a trap representation?

Are there other examples of undefined behavior involving simple bitwise operators for more common architectures?


Solution

  • For one's complement systems, there's explicitly listed the possibility of trap values for those that do not support negative zeros in signed integers (C11 6.2.6.2p4):

    If the implementation does not support negative zeros, the behavior of the &, |, ^, ~, <<, and >> operators with operands that would produce such a value is undefined.

    Then again, one's complement systems are not exactly common; as for example GCC doesn't support any!

    C11 does imply that the implementation-defined and undefined aspects are just allowed for signed types (C11 6.5p4).