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.
Related
#include <stdio.h>
int main(void) {
char i=250;
for(i<0;i++;i=0,printf("%d", i));
return 0;
}
In this program, the output is 0. From what i understand is, a for loop should have the first parameter as initialisation, then condition, then increment. But in this question the initialisation is happening at the last and still the code is giving valid result. Can someone explain how?
The clauses or expressions in a for statement are always interpreted based on where they are (first, second, or third) in the for statement. In this code:
char i=250;
for(i<0;i++;i=0,printf("%d", i));
return 0;
i is set to either 250 (if char is unsigned) or −6 (if char is signed, eight-bit, and typical two’s complement wrapping is used for the conversion from 250 to char). (The C standard permits other possibilities, but they are unusual and are not discussed further in this answer.)
To start the loop, the initial clause i<0 is evaluated. Its result is inconsequential because it is ignored.
To decide whether the loop ends, the test clause i++ is evaluated. This produces either 250 or −6, per the above, and, separately, increments i to either 251 or −5. In either case, the result of the expression is non-zero, so the loop continues.
The body of the loop, ; is evaluated. Since this is an empty statement, it has no effect.
The post-iteration clause, i=0,printf("%d", i) is evaluated. This sets i to 0 and prints i, resulting in output of “0”.
The test clause i++ is evaluated again. Since i is zero, this produces 0, and, separately, increments i to 1. Since the result of the expression is zero, the loop terminates.
return 0; is executed, cause the program to end with a success status.
Short answer to your question "Can we interchange the for loop parameters in C?" is: No .
This code, if not meant to confuse the reader, must be a badly written one.
Walk-through
i is initialized with a value 250
i<0 as the initialization step is ignored
i++ is executed, since the old i is not 0, the loop continues
nothing in the loop body
set i=0 and print its value 0 out
come back to the i++, noting that the previous i value is zero, so loop stops
Actually for loop works in the following way:
for (step 0; step 1; step 3) {
step 2;
}
Here, step 0 is executed only once. Then step 1 -> step 2 -> step 3 -> step 1 and the loop goes on.
a for loop should have the first parameter as initialisation, then condition, then increment.
this is more like a convention. And explaining the for loop in this way makes perfect sense (especially because in step 1, the program executes the statement and continues to step 2 only when it returns true). And so we utilize for loop in this way.
"Can we interchange the for loop parameters in C?"
We can interchange the expressions itself (for whatever reason, for example as experiment because it usually makes no sense to do so), but we can't change the syntax (how an expression is evaluated at a certain place).
A for loop has a fixed syntax following conventionally the form:
for (initializations; condition; in-/decrements)
You can use expressions where you want to but it has quite different effects.
If you place for example the initialization expressions at the second place they are used as condition.
Same goes if you would take the in-/decrements and place them at the second place. Then they would be evaluated as condition, too.
Equivalently, if you would place the expression used as condition at the first or third place, this expression will not be used as the condition anymore.
That's what the C standard says to this topic:
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. Ifclause-1is 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.161)
2 Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a non zero constant.
Source: ISO/IEC 9899:2018 (C18), §6.8.5.3
A for loop for(init; cond; inc) { body } Is basically executed like this:
init;
while(cond) {
body;
inc;
}
For some cases it is possible to switch things, but in the general case it is not.
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 (;;).
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.
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 ;;.
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