-1
vector<int> score= {1,1,1,1,1};
    int z = score.size();
    for(int j=score.size() - 1; j >= z - 5; --j)
        cout << j << endl;

The code right now is fine but causes an error when I replace that line with:

for(int j=score.size() - 1; j >= score.size() - 5; --j)

From the print out, I've deducted it's because j goes to -1 and beyond. My question is why is this happening when I just substituted z for the size() function? The inside of the for loop does not modify size[i].

apluscs
  • 75
  • 5

2 Answers2

4

In this expression:

j >= z - 5

since both j and z are int the comparison works fine since the left hand side can be -1 when j becomes -1.

In this expression:

j >= score.size() - 5

the right hand side is unsigned, so the left hand side is implicitly converted to unsigned as well. When j becomes -1 that conversion gives a very large integer, and the comparison doesn't work as intended.

cigien
  • 57,834
  • 11
  • 73
  • 112
3

size() is unsigned, so size()-1 and size()-5 will also be unsigned (though you are assigning the 1st value to a signed int). j >= score.size() - 5 is comparing a signed integer j to an unsigned integer size()-5.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770