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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With