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.

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. Commented Mar 20, 2016 at 16:12
  • 1
    @CompuChip see also this stackoverflow.com/questions/7594508/… Commented Mar 20, 2016 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". Commented Mar 20, 2016 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. Commented Mar 20, 2016 at 16:40

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@erip: I think you'll find that it's "implementation defined".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.