Bitwise operators and signed types

后端 未结 3 1857
你的背包
你的背包 2021-02-09 07:37

I\'m reading C++ Primer and I\'m slightly confused by a few comments which talk about how Bitwise operators deal with signed types. I\'ll quote:

Quote #1

3条回答
  •  我寻月下人不归
    2021-02-09 07:42

    You're quite correct -- the expression ~'q' << 6 is undefined behavior according to the standard. Its even worse than you state, as the ~ operator is defined as computing "The one's complement" of the value, which is meaningless for a signed (2s-complement) integer -- the term "one's complement" only really means anything for an unsigned integer.

    When doing bitwise operations, if you want strictly well-defined (according to the standard) results, you generally have to ensure that the values being operated on are unsigned. You can do that either with explicit casts, or by using explicitly unsigned constants (U-suffix) in binary operations. Doing a binary operation with a signed and unsigned int is done as unsigned (the signed value is converted to unsigned).

    C and C++ are subtley different with the integer promotions, so you need to be careful here -- C++ will convert a smaller-than-int unsigned value to int (signed) before comparing with the other operand to see what should be done, while C will compare operands first.

提交回复
热议问题