ProgrammingHardIBM · Deloitte pattern

Assume 32-bit int. What is printed?

Assume 32-bit int. What is printed?
unsigned int a = 5;
int b = -3;
printf("%d", a + b > 0);
  1. A. 1
  2. B. 0
  3. C. Compile-time error: cannot mix signed and unsigned in addition
  4. D. Undefined behaviour

Correct answer: A. 1

When an unsigned int and a signed int are combined in arithmetic, the signed operand is converted to unsigned (the usual arithmetic conversions). b=-3 becomes a huge unsigned value (2^32 - 3) when converted; adding that to a=5 wraps around (modulo 2^32) back to 5 + (2^32-3) mod 2^32 = 2, which as an unsigned value is 2, clearly > 0, printing 1 — this happens to work out numerically correctly here (matching the expected -3+5=2), though the TYPE of the comparison is unsigned the whole way through.

More C Programming questions

Exams that ask this topic