-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
  • 714,442
  • 84
  • 1,110
  • 1,523
Bula
  • 2,398
  • 5
  • 28
  • 54

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
  • 14,674
  • 4
  • 34
  • 47
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
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
  • 16,169
  • 4
  • 31
  • 54