简体   繁体   中英

Why for loop is not stopping?

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?

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--){
      |                           ~^~~~~~~~~~~~~~

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM