Vinayaka2000's blog

By Vinayaka2000, history, 2 years ago, In English

Hello codeforces, I'm trying to execute the below piece of code but for some reason, it's getting into an infinite loop and causing a TLE. Please let me know why this is exactly happening ?

#include<bits/stdc++.h>
using namespace std;
int main() {
    vector<int> v;
    for(int i=0; i<v.size()-1; ++i) {
        cout << " inside " << endl;
    }
}

Ideally, the size of the vector should be zero and in the for loop, 0<(0-1) must be false and the for loop must not execute. When I use the below code, its not executing the for loop. I'm sure it's not because of precedence of < over -.

#include<bits/stdc++.h>
using namespace std;
int main() {
    vector<int> v;
    for(int i=0; i<0-1; ++i) {
        cout << " inside " << endl;
    }
}
  • Vote: I like it
  • +3
  • Vote: I do not like it

| Write comment?
»
2 years ago, # |
  Vote: I like it +23 Vote: I do not like it

That's because v.size() returns a size_t variable. So the calculation of v.size() — 1 is done in size_t type. But it is unsigned, so it returns UINT_MAX. And int can not reach it, because it just goes up to INT_MAX and then overflows.

  • »
    »
    2 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Yes. You can use i < ssize(v) - 1 or i < int(v.size()) - 1, then the calculations are performed in signed type ptrdiff_t or int respectively.

    • »
      »
      »
      2 years ago, # ^ |
        Vote: I like it +2 Vote: I do not like it

      additional note on this: ssize is added on C++20, so make sure you are using C++20 before using it

»
2 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Because the return value of fuction "size" is a unsigned int integer, and (unsigned int)0-1 will be a large integer which can reach to $$$2^{32}$$$