Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop missing initialization

Tags:

c

I've seen

for(;;)

and

for ( ; *s != '\0'; s++)

Why is it blank like that. Thanks.

like image 473
Matt Avatar asked Sep 25 '10 02:09

Matt


People also ask

Can I use for loop without initialization?

A 'for' loop can be written without initialization. A 'for' statement usually goes like: for (initialization; test-condition; update).

Is initialization required in for loop?

The initialization is an expression that initializes the loop — it's executed once at the beginning of the loop. The termination expression determines when to terminate the loop. When the expression evaluates to false , the loop terminates.

What happens if don't initialize for loop?

So what happens when there is no initialization and condition parameters in for loop. It looks like this: int i = 0; for( ; ;i++){ } In the case above, it is the infinite loop. If "i" wasn't initialized above, you would get compile time error.

Do you have to initialize in a for loop in C?

No, you do not need to reinitialize x = 0 in your code. That's what the x=0 in your for loop is for. The for loop automatically initializes x to the value you set when starting.


2 Answers

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 to while (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 string s

1 The loop will still be interrupted if there's a break statement in the loop body, or a call to exit(), etc...

like image 80
NullUserException Avatar answered Sep 20 '22 12:09

NullUserException


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.

like image 45
AnT Avatar answered Sep 18 '22 12:09

AnT