Reputation: 7694
Given a string pointer s
in C, what does the following iteration do? i.e in what manner does it iterate over the string?
for (++s ; *s; ++s);
Upvotes: 1
Views: 91
Reputation: 61965
The construct
for (init ; cond ; incr) { body }
roughly translates to (left in pseudo-code)
init
while cond:
body
incr
Thus the original can be viewed as the following, in which case the semantics should be easier to follow:
++s;
while (*s) {
/* no body shown */
++s;
}
Upvotes: 3
Reputation: 106092
for (++s ; *s; ++s)
means that
s
to second element of string, i.e, s[1]
. *s
is \0
or not. *s != 0
, then execute the loop body else go to step 5. s
by 1
. Go to step 3. Upvotes: 4
Reputation: 311068
This for statement
for (++s ; *s; ++s)
in fact is equivalent to the following
for ( int i = 1; s[i] != '\0' ; ++i )
The only difference is that after the first for statement pointer s will be moved along the string while in the second for statamenet it is the index (variable i) that will be changed in iterations.
Upvotes: 1
Reputation: 44888
It just starts iterating from str[1]
instead of str[0]
checking if *str
is a null-terminator.
This works like this: let str
be array of 5 characters.
str->['f']['k']['g']['h']['\0']
++str
is 'k' while str[0]
is 'f'. Then it loops until '\0' is found.
Upvotes: 3