for loop missing initialization
I've seen
for(;;)
and
for ( ; *s != '\0'; s++)
Why is it blank like that. Thanks.
Solution 1:
The for
statement works like:
for (initialization; test-condition; update)
And any or all of those three can be omitted (left blank). So:
for (;;)
is an infinite loop1 equivalent towhile (true)
because there is no test condition. In fact,for (int i=0; ;i++)
would also be an infinite loop1.for ( ; *s != '\0'; s++)
is a loop with no initialization.s
will point to the beginning of (probably) a string and is incremented until it reaches the null character'\0'
denoting end-of-string. This essentially means loop through all characters of the strings
1 The loop will still be interrupted if there's a break
statement in the loop body, or a call to exit()
, etc...
Solution 2:
It is "blank like that" because the author of the code left it blank. The author did not want/need to do anything in the corresponding section of for
statement, so it was left blank.
for (;;)
is a statement that iterates indefinitely (unless it is interrupted from inside cycle body).
for ( ; *s != '\0'; s++)
is a statement that does not need an initialization section, since everything necessary (like the initial value of s
) was already initialized before that for
statement.
Solution 3:
for(;;)
is an infinite loop. It is effectively the exact same as while (true)
.
The reason this works is because when the middle condition in a for
loop is empty, it is interpreted as always being true.
for ( ; *s != '\0'; s++)
is used for reading strings character-by-character. This approach works because every C string ends with a null character (\0
).
Solution 4:
The parts that are blank essentially do nothing. So for (;;)
creates an infinite loop that does nothing at all, and never exits because there is no condition in the loop. Your second example:
for ( ; *s != '\0'; s++)
is just a normal loop without any initialization expression. This relies on the fact that s
already has an initial value and just loops until it reaches the end of the string.
Solution 5:
while(1)
and while(true)
are the same as for(;;)