Weird strlen() behavior?

Правка en2, от Luca1152, 2020-03-28 20:27:39

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 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 look out for it.

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

Теги cpp, for-loop

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en8 Английский Luca1152 2020-03-28 20:36:40 0 (published)
en7 Английский Luca1152 2020-03-28 20:33:01 12 Tiny change: 'wing code (for demo' -> 'wing code snippet (for demo'
en6 Английский Luca1152 2020-03-28 20:31:03 29 Tiny change: 'owing code:\n\n~~~~~' -> 'owing code (for demonstration purposes):\n\n~~~~~'
en5 Английский Luca1152 2020-03-28 20:30:25 9 Tiny change: 'an better look out for i' -> 'an better watch out for i'
en4 Английский Luca1152 2020-03-28 20:29:29 13
en3 Английский Luca1152 2020-03-28 20:28:59 4 Tiny change: ' value of i (0) would' -> ' value of `i` (0) would'
en2 Английский Luca1152 2020-03-28 20:27:39 289
en1 Английский Luca1152 2020-03-28 20:23:11 970 Initial revision (saved to drafts)