-3
#include <stdio.h>

main() {
    unsigned a = -20;
    unsigned b = 10;
    printf("%d\n", (a % b));
    printf("%d\n", (-20 % 10));
}

Output:
6
0

The second printf prints the expected value of 0 while the first printf prints 6. Why this unexpected output with unsigned ints?

Nikunj Banka
  • 11,117
  • 16
  • 74
  • 112
  • 3
    Because `1<<32` is not divisable by 10 ? BTW: *Why* do you use a negative initialiser for an unsigned int? BTW2: printf() has the `%u` specifier for unsigned ints. `%d` is for signed ints. – wildplasser Apr 20 '13 at 15:51

2 Answers2

5

unsigned int can hold values from 0 to UINT_MAX, no negative values. So -20 is converted to -20 + UINT_MAX + 1.

On your system:

(-20 + UINT_MAX + 1) % 10 != -20 % 10
md5
  • 23,373
  • 3
  • 44
  • 93
2

And what are you expecting?

a % b is equivalent to, let's substitute the values and apply the unary - to the unsigned int value of 20, (UINT_MAX-20+1) % 10 and the type of the result is unsigned int and you're printing it with %d, which is wrong. You should use %u here.

Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180