-6
std::vector<int> tmp = ...
for(int i = 0; i <= tmp.size() - 3; i+=2){
    std::cout << "i: " << i << " , tmp.size(): " << tmp.size() << std::endl;
    if(tmp[i] == tmp[i+1]){
        final.push_back(tmp[i] * 2);
    }else{
        final.push_back(tmp[i]);
        final.push_back(tmp[i + 1]);
    }   
    std::cout << "\ntmp.size() at the end of loop: " << tmp.size() << "\n";         
}

I have the following output:

enter image description here

Why does the loop execute as i is clearly much much bigger than tmp.size() ?

Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
Bula
  • 2,078
  • 5
  • 26
  • 53

2 Answers2

9

Since tmp.size() is 1, subtracting 3 from it produces a negative value. That is, subtraction would produce a negative value if it weren't for tmp.size() being size_t, which is unsigned.

When an unsigned is about to go negative on subtraction, it "wraps around" to a very large value. That is why your loop fails to stop. It also explains the "signed to unsigned comparison" warning produced by the compiler*, which should have put you on high alert.

To avoid this problem, move subtraction to the other side, and make it addition:

for (size_t i = 0 ; i+3 <= tmp.size() ; i += 2) {
    ...
}

* If you did not get that warning, change the settings on your compiler to warn you about everything. This saves a lot of time spent in debugging many common problems that are easily detectable by compilers.

Ron
  • 13,936
  • 3
  • 30
  • 47
Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
2

Because your tmp.size() is only 1, in the for loop:

for(int i = 0; i <= tmp.size() - 3; i+=2) { /* ... */ }

tmp.size() - 3 becomes a negative number but with unsigned type, thus a huge number. That's why your i won't stop increasing even it's extremely large.

llllllllll
  • 15,580
  • 4
  • 25
  • 47