Reputation: 147
I have a vector<int> table
and an int index=-833099133
When I write
cout<<table.size()<<endl;
cout<< index%table.size()<<endl;
It gives me :
83
81
however If I write
cout<<index%83<<endl;
output turns out:
-79
Is there anyone to help me why it occurs ? thanks in advance
Upvotes: 0
Views: 155
Reputation:
table.size()
is of type std::vector<int>::size_type
, which is an unsigned type (usually std::size_t
), but the literal 83
is an int
which is signed.
When performing an operation on a signed and an unsigned integer, the signed one is implicitly converted ("promoted") to an unsigned value. That results in a non-negative number which is the original value modulo some power of two (which power is used depends on the width of the unsigned type). In your case, size_t
was 32 bits long, so
-833099133 == 3461868163 (mod 2 ^ 32)
and of course, 3461868163 % 83
is 81, whereas -833099133 % 83
is -79. (-833099133 mod 83
would be +4, but in C++, the %
is not the modulo, but the remainder operator.)
Indeed, if you run the following program on a system where std::size_t
is 32 bits long:
#include <iostream>
int main()
{
int idx = -833099133;
int signed83 = 83;
std::size_t unsigned83 = 83;
std::cout << idx % signed83 << std::endl;
std::cout << idx % unsigned83 << std::endl;
return 0;
}
you will get the same results.
Upvotes: 2