Whats the meaning of "for(;;)" - c

Moin,
I just found a for-loop in some source code.
for (;;) {
// some work
if (condition) {
break;
}
}
How is this for (;;) working ?

This for(;;) is an infinite loop.
As per C11, chapter §6.8.5.3, The for statement,
The statement
for ( clause-1 ; expression-2 ; expression-3 ) statement
behaves as follows: The expression expression-2 is the controlling expression that is
evaluated before each execution of the loop body.[...]
and (emphasis mine)
Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a
nonzero constant.
Also, for the usage of the controlling expression
An iteration statement causes a statement called the loop body to be executed repeatedly
until the controlling expression compares equal to 0. [...]
So, in case, all three are removed, the controlling expression is considered as non-zero, which is TRUE forever, thus essentially making it an infinite loop.

It's an infinite loop, like
while (1)
That was mostly used befroe because some compiler complain when they detected an infinite loop with while(1).
The three part of for is optionnal, so if the initialisation part is missing, then there is no initialization, if the test part is missing, it's assume that's true, etc.

for (;;) {
// some work
if (condition) {
break;
}
}
is equivalent to
do
{
//some work
}while(!condition);

Read this as "forever".
It repeats the block until the condition is met, and the break statement is executed.

It is an infinite loop.
It means the loop will keep execution until you use break or exit function.

Related

Why does this loop go forever?

int main() {
for(3;2;1)
printf("hello\n")
}
I thought this loop wouldn't even be executed. AFAIK we have to define a variable; put a condition; increase/decrease. However in this code none of the things I counted exists. So I think this program should crash. But it goes on forever.
Because the exit condition (2) is always true.
This works because the format of a for statement is
for (clause-1;expression-2;expression-3)
Where clause-1 can be a declaration (e.g. int i = 0) or an expression.
In your case you have three expressions, so the statement is still syntactically valid.
The loop exits when expression-2 evaluates to false (0) which, in your case, it never does since it's a non-zero constant (2).
The stopping conditional expression 2 is never zero.
So the loop runs forever.
AFAIK we have to define a variable; put a condition; increase/decrease. However in this code none of the things I counted exists. So I think this program should crash. But it goes on forever.
While learning about for loops you were likely exposed to a very specific use of a loop, and therefore extrapolated about what may or may not appear there syntactically. But you didn't get the whole picture. There is a standard for that C language, and it is that standard which defines how a loop may be written and how it will behave. For a loop, we may look at §6.8.5 (Iteration statement) to determine the correct behavior:
iteration-statement:
while ( expression ) statement
do statement while ( expression ) ;
for ( expressionopt ; expressionopt ; expressionopt ) statement
for ( declaration expressionopt ; expressionopt ) statement
That's the grammar for all loops. See how the for loop allows an arbitrary expression in all 3 places? Since even 1, 2, and 3 are expressions in C, they can go there. And the standard even tells us what the behavior should be:
An iteration statement causes a statement called the loop body to be executed repeatedly until the controlling expression compares equal to 0.
The statement
for ( clause-1 ; expression-2 ; expression-3 ) statement
behaves as follows: The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body.
So 2 must be evaluated, and compared equal to 0. Which will never occur, hence the behavior you observed.
C is not Bourne shell like in for i in 3 2 1 ; do echo hello ; done
The proper loop is like this:
#include <stdio.h>
int main() {
for(int i = 1; i <=3 ; i++)
printf("hello\n");
}
Here, the conditional expression i <= 3 isn't always true like 2 is. True is any non-zero value.
we know 0 is false and 1 is true. In this case, in conditional statement for( ;2;) is always true like while(2). so it will run infinitely.
.
A for loop doesn’t require the use of any variables. It simply specifies the use of three expressions, each of which may be optional:
for ( expression-1opt ; expression-2opt ; expression-3opt ) statement
First, expression-1 is evaluated (if it is present). This expression typically initializes the condition we’ll test for in expression-2, but it doesn’t have to.
Next, expression-2 is evaluated. If the result of the expression is non-zero, then the loop body will be executed. If expression-2 is not present, then it’s implicitly replaced with a 1.
After the loop body has been executed, expression-3 is evaluated. This expression typically updates the condition we test for in expression-2, but again, it doesn’t have to.
Repeat the last two steps until expression-2 evaluates to zero.
In the case of for ( 1; 2; 3 ) ..., 2 evaluates to non-zero, so the loop body executes. Since that value never changes, the loop runs “forever”. You get the same result with for (;;).

How is for loop parsed internally as in assembly language? [duplicate]

This question already has answers here:
Two semicolons inside a for-loop parentheses
(4 answers)
Closed 4 years ago.
How does a for loop work internally in terms of the machine language when the expressions are not written. For example
int i=0 , j=1;
for(;;)
A for loop with a missing middle expression is an infinite loop.
From section 6.8.5.3 of the C standard:
1 The statement
for ( clause-1 ; expression-2 ; expression-3 ) statement
behaves as follows: The expression expression-2 is the controlling
expression that is evaluated before each execution of the loop body.
The expression expression-3 is evaluated as a void expression after
each execution of the loop body. If clause-1 is a declaration, the
scope of any identifiers it declares is the remainder of the
declaration and the entire loop, including the other two expressions;
it is reached in the order of execution before the first evaluation of
the controlling expression. If clause-1 is an expression, it is
evaluated as a void expression before the first evaluation of the
controlling expression.
2 Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.
Because a missing "expression-2" is replaced with a non-zero constant, and because a non-zero value evaluates to true, this gives you an infinite loop.
All the parts of the for-loop are optional:
initialization: you can do the initialization outside of the loop.
condition: will be true if empty
last part: you can also do nothing.
for(;;) is an infinite loop (if there are no breaks inside the loop).
The expressions which are not present do nothing.
If the initialisation is absent, nothing is initialised.
If the test is absent, nothing is tested (and the body loops forever unless it contains abreak, return, etc.)
If the increment is absent, nothing is incremented.
The for loop contains three clauses. They can be virtually any expression, but the standard way of using it is for(<init>; <loop condition>; <loop variable increment>). All of these are optional: if you omit the loop condition, it will be replaced by a constant that evaluates to true. You could for instance replace
for(int i=0; i<10; i++) {
...
}
with
for(int i=0; i<10; ) {
...
i++;
}
for(;;) is an infinite loop. Any for loop that has second statement omitted is an infinite loop.
There are basically three ways to get out of an infinite loop, break, return and goto.
In most cases you should use break or return, but goto also has its usage.
If you want to just break out of the loop and continue after it, use break.
If you want to quit the function that contains the loop, use return. However, this can be bad practice since it will likely violate the "single exit" practice.
If you want to break out of a nested loop, goto may be appropriate.
And yes, you could exit a loop by calling exit() or simply make the program crash too, but I think you get the point.
Question from comments
for(i<2; i++; )
This does not make much sense. The first expression i<2 will not affect anything and is likely to be optimized away by the compiler. The second expression i++ will evaluate to false if i is 0:
if i has an initial value of 0, the loop body is not evaluated at all.
if i is initially a negative number. The loop iterates until i reaches the value 0, the last iteration occurs with i == 0 and the next test will end the loop.
if i has an unsigned type and is greater than 0. The loop iterates until i reaches the maximum value for its type and wraps to 0, the last iteration occurs with i == 0 and the next test stops the loop. If i is not unsigned, arithmetic overflow will cause undefined behavior, which is bad: the loop may stop or continue indefinitely, depending on the compiler choices, or anything else may occur.

Blank 'For' Loop Giving Output

I encountered a strange FOR LOOP question in the book. Here is the code for the loop -
#include<stdio.h>
int main()
{
int i=1,j=1;
for(;;)
{
if(i>5)
break;
else
j+=i;
printf("%d\n",j);
i+=j;
}
return 0;
}
The program prints 2 & 5 as the output. Now could anyone please explain how this for loop is executing?
That for loop is a classic idiom for a non-terminating loop. It's what you use when you want a loop that never terminates, or whose termination is controlled by control flow statements inside the loop. The latter is the case here.
for(;;)
All parts of the for loop are empty. They key to understanding why it is a non-terminating loop is the empty controlling expression in the for statement.
The standard (6.8.5.3 The for statement) says, with my emphasis:
The statement
for ( clause-1 ; expression-2 ; expression-3 ) statement
behaves as follows: The expression expression-2 is the controlling
expression that is evaluated before each execution of the loop body.
The expression expression-3 is evaluated as a void expression after
each execution of the loop body. If clause-1 is a declaration, the
scope of any identifiers it declares is the remainder of the
declaration and the entire loop, including the other two expressions;
it is reached in the order of execution before the first evaluation of
the controlling expression. If clause-1 is an expression, it is
evaluated as a void expression before the first evaluation of the
controlling expression.158)
Both clause-1 and expression-3 can be omitted. An omitted
expression-2 is replaced by a nonzero constant.
And this means that your loop will never terminate due to the controlling expression part of the for statement.
for(;;)
is a for loop which performs no initialisation, has no exit condition and performs no post-action.
It will loop forever unless code inside the loop contains a condition that can result in break being called.
Your loop is equivalent to
int i,j;
for(i=1, j=1 ;i<=5 ;i+=j) {
j+=i;
printf("%d\n",j);
}
for(;;) is equivalent to while(true) (or while(1) in old-school C), both of whose terminations are only controlled by the statements inside them.
Edit:
To rehash a couple of old jokes (borrowed from here):
Don't use for (;;) {} — it makes the statement cry.
Unless, of course, you #define EVER ;;.

a case of for loop in c

I came across the following question :
How many times will the following for loop run -
for(;0;)
printf("hello");
I executed and it runs 1 time . I am not able to understand how?
This will not execute even for 1 time. I guess you have a bad compiler?
Ok. I think you are using Turbo C ;-)
EDIT:
From C99 standard:
6.8.5.3 The for statement 1 The statement
for ( clause-1 ; expression-2 ; expression-3 )
statement behaves as follows: The expression expression-2 is the
controlling expression that is evaluated before each execution of the
loop body. The expression expression-3 is evaluated as a void
expression after each execution of the loop body. If clause-1 is a
declaration, the scope of any variables it declares is the remainder
of the declaration and the entire loop, including the other two
expressions; it is reached in the order of execution before the first
evaluation of the controlling expression. If clause-1 is an
expression, it is evaluated as a void expression before the first
evaluation of the controlling expression.134)
It clearly states that condition is evaluated first before executing the loop. Any standard conforming compiler should not execute the loop for(;0;) {} even once.
Either the code you copied here is not really what is in your .c file or you have a buggy compiler.
Maybe you have an additional semicolon?: for(;0;); printf("!"); will print once.
for loops are defined as:
for(startExpression; testExpression; countExpression)
{
block of code;
}
startExpression is evaluated before the code;
testExpression is evaluated before the code;
countExpression is evaluated after code;
Decoding:
for(;0;)
Means
no startExpression
testExpression evaluated to false, therefore loop exits.
Edited to show correct for loop decoding.
The code as written above will never enter the for loop.
Check the code on ideone link.
My be this not what you have in your souce code, you probably typed a ; after for without noticing it like this:
for(;0;);
printf("hello");
In that case your program will print "hello".
Since the expression is 0, it is taken to be false. So, in this case the loop runs 0 times.

What is the full "for" loop syntax in C?

I have seen some very weird for loops when reading other people's code. I have been trying to search for a full syntax explanation for the for loop in C but it is very hard because the word "for" appears in unrelated sentences making the search almost impossible to Google effectively.
This question came to my mind after reading this thread which made me curious again.
The for here:
for(p=0;p+=(a&1)*b,a!=1;a>>=1,b<<=1);
In the middle condition there is a comma separating the two pieces of code, what does this comma do? The comma on the right side I understand as it makes both a>>=1 and b<<=1.
But within a loop exit condition, what happens? Does it exit when p==0, when a==1 or when both happen?
It would be great if anyone could help me understand this and maybe point me in the direction of a full for loop syntax description.
The comma is not exclusive of for loops; it is the comma operator.
x = (a, b);
will do first a, then b, then set x to the value of b.
The for syntax is:
for (init; condition; increment)
...
Which is somewhat (ignoring continue and break for now) equivalent to:
init;
while (condition) {
...
increment;
}
So your for loop example is (again ignoring continue and break) equivalent to
p=0;
while (p+=(a&1)*b,a!=1) {
...
a>>=1,b<<=1;
}
Which acts as if it were (again ignoring continue and break):
p=0;
while (true) {
p+=(a&1)*b;
if (a == 1) break;
...
a>>=1;
b<<=1;
}
Two extra details of the for loop which were not in the simplified conversion to a while loop above:
If the condition is omitted, it is always true (resulting in an infinite loop unless a break, goto, or something else breaks the loop).
A continue acts as if it were a goto to a label just before the increment, unlike a continue in the while loop which would skip the increment.
Also, an important detail about the comma operator: it is a sequence point, like && and || (which is why I can split it in separate statements and keep its meaning intact).
Changes in C99
The C99 standard introduces a couple of nuances not mentioned earlier in this explanation (which is very good for C89/C90).
First, all loops are blocks in their own right. Effectively,
for (...) { ... }
is itself wrapped in a pair of braces
{
for (...) { ... }
}
The standard sayeth:
ISO/IEC 9899:1999 §6.8.5 Iteration statements
¶5 An iteration statement is a block whose scope is a strict subset of the scope of its
enclosing block. The loop body is also a block whose scope is a strict subset of the scope
of the iteration statement.
This is also described in the Rationale in terms of the extra set of braces.
Secondly, the init portion in C99 can be a (single) declaration, as in
for (int i = 0; i < sizeof(something); i++) { ... }
Now the 'block wrapped around the loop' comes into its own; it explains why the variable i cannot be accessed outside the loop. You can declare more than one variable, but they must all be of the same type:
for (int i = 0, j = sizeof(something); i < j; i++, j--) { ... }
The standard sayeth:
ISO/IEC 9899:1999 §6.8.5.3 The for statement
The statement
for ( clause-1 ; expression-2 ; expression-3 ) statement
behaves as follows: The expression expression-2 is the controlling expression that is
evaluated before each execution of the loop body. The expression expression-3 is
evaluated as a void expression after each execution of the loop body. If clause-1 is a
declaration, the scope of any variables it declares is the remainder of the declaration and
the entire loop, including the other two expressions; it is reached in the order of execution
before the first evaluation of the controlling expression. If clause-1 is an expression, it is
evaluated as a void expression before the first evaluation of the controlling expression.133)
Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a
nonzero constant.
133) Thus, clause-1 specifies initialization for the loop, possibly declaring one or more variables for use in
the loop; the controlling expression, expression-2, specifies an evaluation made before each iteration,
such that execution of the loop continues until the expression compares equal to 0; and expression-3
specifies an operation (such as incrementing) that is performed after each iteration.
The comma simply separates two expressions and is valid anywhere in C where a normal expression is allowed. These are executed in order from left to right. The value of the rightmost expression is the value of the overall expression.
for loops consist of three parts, any of which may also be empty; one (the first) is executed at the beginning, and one (the third) at the end of each iteration. These parts usually initialize and increment a counter, respectively; but they may do anything.
The second part is a test that is executed at the beginning of each execution. If the test yields false, the loop is aborted. That's all there is to it.
The C style for loop consists of three expressions:
for (initializer; condition; counter) statement_or_statement_block;
The initializer runs once, when the loop starts.
The condition is checked before each iteration. The loop runs as long it evaluates to true.
The counter runs once after each iteration.
Each of these parts can be an expression valid in the language you write the loop in. That means they can be used more creatively. Anything you want to do beforehand can go into the initializer, anything you want to do in between can go into the condition or the counter, up to the point where the loop has no body anymore.
To achieve that, the comma operator comes in very handy. It allows you to chain expressions together to form a single new expression. Most of the time it is used that way in a for loop, the other implications of the comma operator (e.g. value assignment considerations) play a minor role.
Even though you can do clever things by using syntax creatively - I would stay clear of it until I find a really good reason to do so. Playing code golf with for loops makes code harder to read and understand (and maintain).
The wikipedia has a nice article on the for loop as well.
Everything is optional in a for loop. We can initialize more than one variable, we can check for more than one condition, we can iterate more than one variable using the comma operator.
The following for loop will take you into an infinite loop. Be careful by checking the condition.
for(;;)
Konrad mentioned the key point that I'd like to repeat: The value of the rightmost expression is the value of the overall expression.
A Gnu compiler stated this warning when I put two tests in the "condition" section of the for loop
warning: left-hand operand of comma expression has no effect
What I really intended for the "condition" was two tests with an "&&" between. Per Konrad's statement, only the test on to the right of the comma would affect the condition.
Formal syntax of the for loop:
for (init-statement condition; iteration-expression)
statement
Corresponding flowchart:
Equivalent program:
{
init-statement
while (condition) {
statement
iteration-expression;
}
}
Except that
Names declared by init-statement (if init-statement is a declaration) and names declared by condition (if condition is a declaration) are in the same scope (which is also the scope of statement).
continue in statement will execute iteration-expression.
Empty condition is equivalent to while (true).
the for loop is execution for particular time for(;;)
the syntex for for loop
for(;;)
OR
for (initializer; condition; counter)
e.g (rmv=1;rmv<=15;rmv++)
execution to 15 times in for block
1.first initializ the value because start the value
(e.g)rmv=1 or rmv=2
2.second statement is test the condition is true or false ,the condition true no.of time execution the for loop and the condition is false terminate for block,
e.g i=5;i<=10 the condition is true
i=10;i<10 the condition is false terminate for block,
3.third is increment or decrement
(e.g)rmv++ or ++rmv

Resources