Reputation: 148
I have a for
loop in my program that is not stopping:
vector<int> v;
int k = 1;
v.push_back(1);
for(int i=v.size()-1; i>=(v.size()-k); i--){
cout << i << " " << v.size() - k << endl;
}
When I execute the above program, it keeps running inside the for
loop. The output of the for
loop is as below:
0 0
-1 0
-2 0
-3 0
-4 0
.
.
.
As per the output, value of i
is decreasing and value of v.size()-k
is 0. So, i >= v.size()-k
is false, which should stop the for
loop to execute after the first round, But the for
loop doesn't stop executing.
Can someone help me understand this issue?
Upvotes: 1
Views: 168
Reputation: 182753
You are checking if i
is greater than or equal to zero. But since size()
returns an unsigned, you are comparing i
to an unsigned zero. To do the comparison, i
is converted to the same unsigned type that size()
returns. Well, every unsigned integral value is greater than or equal to zero. So whatever value i
has, the comparison is true.
The size()
function has to return a type large enough to hold the maximum number of entries that might be in a vector. That can be larger than the largest value an int
can hold. On typical modern platforms, int
might be a 32-bit signed type while size()
returns a 64-bit unsigned.
Here's the warning from my compiler:
a.cpp: In function ‘int main()’:
a.cpp:10:28: warning: comparison of integer expressions of different signedness:
‘int’ and ‘std::vector<int>::size_type’
{aka ‘long unsigned int’} [-Wsign-compare]
10 | for(int i=v.size()-1; i>=(v.size()-k); i--){
| ~^~~~~~~~~~~~~~
Upvotes: 6