简体   繁体   中英

For loop in c++ is not running while using this way: for(int i=-1;i<vector.size();i++) cout << i << endl;

I have a particular use case where I have to initialize i value in for loop to -1 and write the exiting condition based on vector size. But the problem is the loop is not getting executed at all. This is the code.

#include <bits/stdc++.h>
using namespace std;

int main()
{
    vector<int> vec = { 1, 2, 3, 4, 5 };
    for(int i=-1;i<vec.size();i++) cout << i << " ";
    return 0;
}

But I am able to do like this.

#include <bits/stdc++.h>
using namespace std;

int main()
{
    vector<int> vec = { 1, 2, 3, 4, 5 };
    int size = vec.size();
    for(int i=-1;i<size;i++) cout << i << " ";
    return 0;
}

Can anyone explain this weird behavior or am I doing something wrong there?

i<size() in the first snippet compares a signed int i; to an unsigned size_t size; ( size_t is the typical typedef for vector::size_type )

When the compiler sees that comparison, it converts the int to an unsigned value. Typically something like 2^64 - 1 , for your first value of -1 . This value is much bigger than 5, so the loop doesn't run.

Take-away: Don't compare signed and unsigned value with less-than or greater-than.

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