tags:

views:

133

answers:

7

Given this loop, why is there a semi colon at the end?

for(s = string; *s == ' '; s++)
    ;

thanks

edit * so is it possible to reverse this procedure so it starts at the end of a string and checks for a space and decreases until it finds a charachter?

A: 

It causes the loop to do nothing. All that happens is that the pointer is advanced.

Ignacio Vazquez-Abrams
+3  A: 

The semicolon means that nothing is done inside the loop. In your code the loop just loops until the character in the string is not a space. That is, after that line s points to the first character in the string that is not a space.

Marius
+3  A: 

The semicolon makes an empty statement in the loop. This loop searches for the first non-blank char in string.

+5  A: 

It is an empty statement, which is a no-op in C. It's as if you had said:

for(s = string; *s == ' '; s++)
{
    // do nothing
}

You use this when everything can be done in the for( ... ) construct itself - the C grammar requires that there be a controlled statement, but there is nothing for it to do.

anon
A: 

There has to be a statement or block as the "body" of the for loop. This is what is executed each time through the loop (as long as s is still pointing to a space).

A semicolon on its own is the empty statement -- that is, nothing happens in the loop body, just the s++ on the for loop line.

Paul Stephenson
+1  A: 

Because in C (and others) for grammar is: for (init; condition; step) body

Where body can be a closure ( a block of code in {}), but body can also be a empty with ;

den bardadym
+1  A: 

I'd like to point out that the loop could be written like this to make it more explicit what is going on and increase readability:

 for(s = string; *s == ' ';)
     s++;

Or using a while loop:

 s = string;
 while(*s == ' ')
     s++;

But I think the first approach with the empty body is more "c-idiomatic" (and harder to read).

Martin Wickman
The increase in readability is in your eyes only, IMHO. The fact that the original form is idiomatic is what makes it easy for experienced C programmers to read.
anon
well, the *only* reason we are talking about it is because the OP had problem understanding it...
Martin Wickman