unsigned to signed conversion

前端 未结 3 1286
再見小時候
再見小時候 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 08:59

    It's because there is a heirarchy of data types when performing implicit conversions, unsigned integers have a higher precedence than signed integers so b and c are being cast back to unsigned integers which is why you're seeing the results you are.

    If you are unsure of the types but know the type of the result you want then you should cast both x and y as you did in d.

    This has a really good explanation of type conversion:

    http://www.learncpp.com/cpp-tutorial/44-type-conversion-and-casting/

提交回复
热议问题