unsigned to signed conversion

前端 未结 3 1259
再見小時候
再見小時候 2020-12-03 08:16

Consider the following:

#include 

int main() {

    unsigned int x = 3;
    unsigned int y = 5;

    std::cout << \"a: \" << x -         


        
3条回答
  •  情深已故
    2020-12-03 09:00

    In arithmetic operations, if any of the operand is unsigned, the other operand converts to unsigned (if its signed), and the result of the operations will be unsigned also.

    Also, casting unsigned to signed and then doing the operation doesn't change the bit representation of the operand. On a two's complement architecture (i.e almost every modern architecture), (int)x has same bit representation as x has, only their interpretation changes when calculating their value in decimal system. But the important point is that the arithmetic operation is performed on the bit representations (not on their values in decimal system). And since the casting doesn't change the bit representation, the bit representation of the result will also NOT change.

    C++03 Standard says in §5/9:

    Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

    [...]

    Otherwise, if either operand is unsigned, the other shall be converted to unsigned.

提交回复
热议问题