wrap-around functionality in unsigned short

64 Views Asked by At

Whenever I run the code :

signed short ssh{-3};
unsigned short ussh{1};

std::cout << ussh + ssh << '\n'; // should be (65535-2+1) = 65534

I get the output as -2 instead of 65534 while the same wrap-around functionality works well with the unsigned long and unsigned int.

Is unsigned short prohibited to perform wrap around or it is just promoted into int??

2

There are 2 best solutions below

0
Mark Ransom On BEST ANSWER

The rules for integer promotion are very clear for C++. Both values are going to be promoted to a type that has a range that can accept the values without change, which in your case is int.

Nothing is wrapping.

0
Swift - Friday Pie On

By default, result of arithmetic operation would get promoted to type result can fit in. For bitwise and integer arithmetic operations it's an int or closest "bigger" type which can fit a result without altering it value .

Consider that your code is an equivalent of

{
   auto some_value = ussh + ssh;    // auto should be signed and an int at least
   std::cout << some_value << '\n';
}

Behavior you're looking for can be expressed in this or similar way:

// For complement of 2 it can be considered ssh being 
// cast to unsigned short
ussh += ssh;  
std::cout << ussh << '\n';