-
modulo a size_t
Hi, a curious question. Why is the value of an int % a size_t strange?
Code:
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
int main(){
vector<int> somevec;
somevec.push_back(0);
somevec.push_back(0);
somevec.push_back(0);
somevec.push_back(0);
somevec.push_back(0);
somevec.push_back(0);
int moo = -1 % 6;
int boo = -1 % somevec.size();
int zoo = -1 % (int)(somevec.size());
cout << "mm : " << moo << endl;
cout << "m2 : " << boo << endl;
cout << "m3 : " << zoo << endl;
}
They should be the same.. right?
Cheers
-
I get
Code:
mm : -1
m2 : 3
m3 : -1
For those of you who don't want to run the code. size() is unsigned, in contrast to the other types shown. That'll all I've got.
-
When you operate on a signed and an unsigned, the signed argument is converted to unsigned. So -1 is converted to unsigned int, value 4294967295.
4294967295 % 6 == 3.
-
When you do arithmetic with mixed types, one value is cast to some other type according to some rules. If one operand is signed and the other unsigned, the signed value is cast to unsigned.
And a hint:
Code:
vector<int> somevec(6);
//somevec.push_back(0);
//somevec.push_back(0);
//somevec.push_back(0);
//somevec.push_back(0);
//somevec.push_back(0);
//somevec.push_back(0);
-
ahh, I see. Didn't think of that. Thanks :)
p.s I was thinking of putting vector.resize() but I guess I'd still miss that constructor thing.. heh