-1

The following snippet produces an infinite loop:

vector<int> nums = {};
for (int i=0; i<(nums.size()-1); ++i) {
    cout << i << endl;
}

while the following, correctly, does not even start:

for (int i=0; i<int(nums.size()-1); ++i) {
    cout << i << endl;
}

Why?

Pippo
  • 1,521
  • 3
  • 21
  • 39
  • `nums.size()` return type is unsigned. #1 snippet is not infinite loop though. – Ch3steR May 07 '22 at 17:57
  • The first one is unsigned integer overflow and undefined behaviour caused by signed integer overflow. The second one is undefined behaviour caused by signed integer overflow. – 273K May 07 '22 at 17:58
  • I believe it's because nums.size() is an unsigned integer. Hence, the expression, `nums.size()-1` may be interpreted as unsigned. (i.e `0-1 == 0xffffffff`) – selbie May 07 '22 at 17:58
  • Instead of `i – selbie May 07 '22 at 18:02
  • 1
    @273K I'm not sure why you voted to close this as "not reproducible or caused by a typo". Please use the appropriate close reasons for questions, as it's less confusing to both the OP and other users. – cigien May 07 '22 at 18:02

0 Answers0