6

For example the code below

int a = -7777;
int b = 10;
cout<< a % b<<endl;
cout<<(a+b)%b<<endl;
cout<< -7777%10 <<endl;

The results are:

-7
-7
-7

but if I changed the type of b to unsigned int, it has different values;

int a = -7777;
unsigned int b = 10;
cout<< a % b<<endl;
cout<<(a+b)%b<<endl;
cout<< -7777%10 <<endl;

The resutls are

9
9
-7

Could any body advise how it is working here? How do the differences come?

Btw: I am using C++ in Xcode latest version.

Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90
skydoor
  • 25,218
  • 52
  • 147
  • 201
  • And the interesting observation is, neither possibility gives the mathematically correct result 3 (the solution for `b` to `-7777 = 10 * a + b` where `a` is any integer and `0 <= b < 10`). Although of course `-7` is closest because it is equivalent to `3` modulo 10. – CompuChip Mar 20 '16 at 16:12
  • 1
    @CompuChip see also this http://stackoverflow.com/questions/7594508/modulo-operator-with-negative-values – Giorgi Moniava Mar 20 '16 at 16:15
  • @CompuChip: When it comes to negative numbers, there are two ways to do modulo. One results in -7, and one results in 3. Both are accurate, and for a long time, some compilers did it one way, and other compilers did it the other way. C++11 finally standardized one as "correct". – Mooing Duck Mar 20 '16 at 16:30
  • @CompuChip - 'least non-negative residue' `(0 <= r < |b|)` would have been the superior choice; mathematically, it exhibits a regularity the other conventions don't, and leaves no ambiguity. That doesn't make the other answers 'incorrect' (mod 10) in this case - they're just different conventions. – Brett Hale Mar 20 '16 at 16:40

1 Answers1

5

cout<< a % b << endl;

In the above line a is converted to unsigned type (since you declared b as unsigned) due to usual arithmetic conversions. When I interpreted binary representation of -7777 on my machine as positive value it yields, 4294959519, which might explain the result of 9 in your case.

In this case:

cout<< -7777%10 <<endl;

no promotion is done since both literals are of type int and you see result -7.

Community
  • 1
  • 1
Giorgi Moniava
  • 27,046
  • 9
  • 53
  • 90