c++ safeness of code with implicit conversion between signed and unsigned

  • A+
Category:Languages

According to the rules on implicit conversions between signed and unsigned integer types, discussed here and here, when summing an unsigned int with a int, the signed int is first converted to an unsigned int.

Consider, e.g., the following minimal program

#include <iostream>  int main() {    unsigned int n = 2;    int x = -1;     std::cout << n + x << std::endl;     return 0; } 

The output of the program is, nevertheless, 1 as expected: x is converted first to an unsigned int, and the sum with n leads to an integer overflow, giving the "right" answer.

In a code like the previous one, if I know for sure that n + x is positive, can I assume that the sum of unsigned int n and int x gives the expected value?

 


In a code like the previous one, if I know for sure that n + x is positive, can I assume that the sum of unsigned int n and int x gives the expected value?

Yes.

First, the signed value converted to unsigned, using modulo arithmetic:

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type).

Then two unsigned values will be added using modulo arithmetic:

Unsigned integers shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer.

This means that you'll get the expected answer.

Even, if the result would be negative in the mathematical sense, the result in C++ would be a number which is modulo-equal to the negative number.

Note that I've supposed here that you add two same-sized integers.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: