Consider the following code:
#include <bits/stdc++.h>
using namespace std;
int main(){
char s[] = "x";
for (int i=0; i<=strlen(s)-4; i++){
cout << s[i];
}
return 0;
}
You'd expect the for
to never loop at all, since the initial value of i (0) would be higher than that of strlen(s)-4
(-3) right? But no, it becomes an infinite loop... You can test it yourself. Here are the Watches from a random state in the loop:
After searching about this issue a bit, I read that it isn't a good practice to put the strlen()
into a for
as a condition, as it takes time to compute it each loop. So yes, from now on I will avoid this approach, either by storing the value into a variable beforehand, or by checking using s[i]
.
But... What if this whatever causes this occurs in some other context, that doesn't ?