2

When adding signed and unsigned values we follow these two rules (from https://stackoverflow.com/a/2280810/1073672)

Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.

Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.

Which of the above rules will be triggered for:

unsigned int ui = 4;
ui = ui + 532; 
Community
  • 1
  • 1
user10607
  • 3,011
  • 4
  • 24
  • 31

1 Answers1

2

The type of the constant 532 is int, which is signed.

Looking at the first rule, since unsigned int and int have the same rank, then the unsigned type's rank is greater than or equal to the signed type's. The first rule matches. The signed 532 is converted to unsigned int before the addition.

Even if the first rule hadn't matched, the addition cannot match the second rule, because a signed int cannot represent all the values of an unsigned int. (There are the same number of possible signed ints as unsigned ints, but for example, -1 is a signed int but not an unsigned int, therefore there must be at least one unsigned int that cannot be represented as a signed int.)

Dan Getz
  • 8,774
  • 6
  • 30
  • 64
  • 1
    A conforming implementation *could* make the range of `int` a subset of the range of `unsigned int`. The sign bit for `int` would have to be a padding bit for `unsigned int`. This might be reasonable for a system that only has hardware support for signed integers. (I know of no such current systems in real life.) – Keith Thompson Nov 04 '14 at 17:02