Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

c++ - unsigned to signed conversion

Consider the following:

#include <iostream>

int main() {

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

    std::cout << "a: " << x - y        << std::endl;

    std::cout << "b: " << ((int)x) - y << std::endl;

    std::cout << "c: " << x - ((int)y) << std::endl;

    std::cout << "d: " << ((int)x) - ((int)y) << std::endl;

}

$ g++ -Wconversion -Wall uint_stackoverflow.cc -o uint_stackoverflow && ./uint_stackoverflow
a: 4294967294
b: 4294967294
c: 4294967294
d: -2

I understand why "a" doesn't give the expected result. But why "b" and "c" fail puzzles me. For "b" I thought after casting "x" to "int" the result will be "int" again.

Could you please enlighten me?

edit: Shouldn't the compiler warn? g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5

Thanks,

Somebody

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...