Weird strlen() behavior in C++ for-loops?

Revision en7, by Luca1152, 2020-03-28 20:33:01

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? :)

Tags cpp, for-loop

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en8 English Luca1152 2020-03-28 20:36:40 0 (published)
en7 English Luca1152 2020-03-28 20:33:01 12 Tiny change: 'wing code (for demo' -> 'wing code snippet (for demo'
en6 English Luca1152 2020-03-28 20:31:03 29 Tiny change: 'owing code:\n\n~~~~~' -> 'owing code (for demonstration purposes):\n\n~~~~~'
en5 English Luca1152 2020-03-28 20:30:25 9 Tiny change: 'an better look out for i' -> 'an better watch out for i'
en4 English Luca1152 2020-03-28 20:29:29 13
en3 English Luca1152 2020-03-28 20:28:59 4 Tiny change: ' value of i (0) would' -> ' value of `i` (0) would'
en2 English Luca1152 2020-03-28 20:27:39 289
en1 English Luca1152 2020-03-28 20:23:11 970 Initial revision (saved to drafts)