ARF
ARF

Reputation: 7694

How does this iteration work: for(++s ; *s; ++s)

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

Answers (4)

user2864740
user2864740

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

haccks
haccks

Reputation: 106092

for (++s ; *s; ++s) means that

  1. Increment pointer s to second element of string, i.e, s[1].
  2. Check whether *s is \0 or not.
  3. If *s != 0, then execute the loop body else go to step 5.
  4. Increment s by 1. Go to step 3.
  5. Exit loop.

Upvotes: 4

Vlad from Moscow
Vlad from Moscow

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

ForceBru
ForceBru

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

Related Questions