Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 738
skydoor Avatar asked Mar 20 '16 15:03

skydoor


1 Answers

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.

like image 88
Giorgi Moniava Avatar answered Oct 19 '22 00:10

Giorgi Moniava