Applying modulo operation on a value of type int and unsigned integer
Asked Answered
F

1

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.

Francinafrancine answered 20/3, 2016 at 15:30 Comment(4)
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.Presber
@Presber see also this #7595008Realtor
@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".Ritaritardando
@Presber - '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.Impure
R
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.

Realtor answered 20/3, 2016 at 15:34 Comment(1)
@erip: I think you'll find that it's "implementation defined".Semitrailer

© 2022 - 2024 — McMap. All rights reserved.