Why does this loop go forever? - c

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 (;;).

Related

Can we interchange the for loop parameters in C?

#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.

What will be the output of this code and can you explain the step by step progression?

I tried this code and got the output below. But I don't understood how it came.
What is the logic involved in this snippet of code? Can you explain?
Also when ++i is replaced by i++ it gives different output??
int main()
{
char i= 0;
for(i<=5 && i>=-1;++i;i>0)
printf("%d\n",i);
printf("\n");
return 0;
}
Output:
1 2 3 .... 126 127 -128 -127 .... 2 1.
it is because of the for loop you have written
for(i<=5 && i>=-1;++i;i>0)
the first option in for loop is executed once. it doesn't check whether the condition is true or not, nor doesn't control the loop execution. even though the expression evaluated to 0, the loop starts executing.
the second part is executed every time the loop begins, and it is the loop breaking condition. that is, if this expression results 0, it breaks.
the third section executes every time, again, doesn't affect the loop execution.
NOw let's analyze your code.
i is initialized to 0 before entering the loop.
initializer in for loop does a condition check, i<=5 && i>=-1 but doesn't change the value of i.
the condition section does an increment to the variable i, which happens every time it enters the loop. so the value goes from 0,1,2,..127,-128,-127...-1 ( since it is signed char which ranges from -128 to 127) and then reaches 0, which means false. when it evaluates to 0, the for loop breaks. thus the output you got.
the 3rd section is again a condition, which doesn't update the value.
you might want to check the syntax of loop, and what is the output you are expecting.
This is what the C standard says about for loops:
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.
The for loop starts printing with i equal to 1. i wraps around after reaching the max value possible for the char datatype. The loop terminates when expression-2 i.e. ++i in this case is 0. ++i evaluates to 0 when i is -1.
Also note that overflowing a signed number results in undefined behaviour. The char data type may be signed or unsigned based on your system.

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.

Whats the meaning of "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.

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.

Resources