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;
}
}
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.
Yes. You can use
i < ssize(v) - 1
ori < int(v.size()) - 1
, then the calculations are performed in signed typeptrdiff_t
orint
respectively.additional note on this:
ssize
is added on C++20, so make sure you are using C++20 before using itBecause 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}$$$