for loop shape

Hello!
Please, what is the exact meaning of s[i] in the middle of the for loop?
Many thanks!

1
2
3
4
5
6
7
8
9
10
11
 //strlen function
//input: s= sequence of chars
//output: lenght of the sequence


int strlen(const char* s){
int i;
for (i=0,s[i]; i++);
return i
}


if we have char s[]="Happy New Year!";

strlen is of course 15;
and
"const char*s" is pointer (adress) of the first character in the sequence ,isn't it?
None of this code looks correct. =/
Well, there are several careless errors in the code. If we first debug it and correct the errors, we get this code:
1
2
3
4
5
6
int strlen(const char* s)
{
    int i;
    for (i=0; s[i]; i++);
    return i;
}


the s[i] is the condition to be tested, just the same as in any other for loop.

The code is equivalent to:
1
2
3
4
5
6
7
int strlen(const char* s)
{
    int i = 0;
    while (s[i])
        i++;
    return i;
}

The loop will execute while the condition (s[i]) is true. This follows the normal rules, that a non-zero value is true and a value of zero is false. Hence the loop will execute until the zero byte is found which marks the end of the string.
Thanks, Chervil, finnaly clear!!!
Topic archived. No new replies allowed.