Luca1152's blog

By Luca1152, history, 4 years ago, In English

Consider the following code snippet (for demonstration purposes):

#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 strlen() into a for as a condition, since 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 if I reached the end using s[i].

But... What if whatever causes this occurs in some other context that doesn't involve strlen()? I'd like to understand why this happens in the first place, so I can better watch out for it.

So could somebody help me understand what is going on here? :)

Full text and comments »

  • Vote: I like it
  • +8
  • Vote: I do not like it