-1

I've been read a book said if you minus an unsigned value a signed value, the signed value will cast to unsigned, but the signed long long will not cast, for example

#include <iostream>

int main()
{
    unsigned int a = 10;
    long long b = 20;
    std::cout << a - b << std::endl;
    return 0;
}

the result is -10, not a very big value, will the C++ fix it in future?

Alan Jian
  • 559
  • 3
  • 12
  • The value of the smaller type will generally be converted to the same type as the larger type. In short, the `unsigned int` variable `a` will be converted to type `long long`. Otherwise there will be possible data-loss if the opposite was true. [This integral conversion reference](https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_conversions) might be good to read. – Some programmer dude Jun 16 '20 at 10:27
  • Oh, so if long type is bigger than int, the int will cast to signed long? – Alan Jian Jun 16 '20 at 10:29
  • Yes, thank you provide reference – Alan Jian Jun 16 '20 at 10:38

1 Answers1

0

One of the rules of type conversion is, if one of the types can represent all the values of the other type, the "smaller" type is converted to the "bigger" type. So, if unsigned int is a 32-bit type, and long long is a 64-bit type (which is often the case), the former will be converted to the latter.

Yes, unsigned is often preferred over signed when the types have the same "rank" (i.e. bit-width), but the rule on "smaller" and "bigger" types is more important.

C++ has complicated rules for type conversion when doing arithmetic on two values of different types. If the correctness of your code depends on these rules, your code can break in obscure ways, so better use explicit type conversions!

anatolyg
  • 24,991
  • 8
  • 55
  • 121
  • Is the cast value rank int = long < unsigned = unsigned long < long long < unsigned long long in 64bit? – Alan Jian Jun 16 '20 at 10:36
  • Usually, "[unsigned] long long" types are 64-bit, and "[unsigned] [long] int" are 32-bit. Some platforms have 64-bit "int" types (I have never used these). Conversion rules will reflect bit-size. So `signed long` - `unsigned int` = `unsigned long`. But you can make good code without knowing these details, just by being aware that they exist, and doing explicit conversion when needed. – anatolyg Jun 16 '20 at 10:49
  • int = long = unsigned = unsigned long < long long = unsigned long long – anatolyg Jun 16 '20 at 10:53