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 (;;).
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.
for(i=1;i=-1;i++)
if(i<5) break;
printf("%d\n",i);
i was asked to write the output of the following code, i could not understand as the second argument should have been a condition, but here it was an assignment,
output: -1
i cant understand how it is possible, so i tried to experiment with the code
int i=1;
while(i=-1)
{
printf("condition is true\n");
if(i<5) break;
}
printf("%d\n",i);
the output of the following code is
output: condition is true
-1
can anyone explain how the above two codes work
and how is while(i=-1) evaluated to TRUE??
The condition is always true. Because the value of an assignment statement is the value assigned. So -1 is non-zero and non-zero value is considered as true in c so it is always true.
The correct usage would be == which compares the value and returns 1 or 0 based on the equality or non-equality.
So here when you did i = -1 and put in the while loop condition - it boils down to
while( -1 ){
...
/* break here */
}
And as -1 is considered as true in c because of it being nonzero - the loop condition evaluates to true.
The break statement here is given here so that this loop doesn't turn to be an infinite loop.
The syntax of a for loop in C is
for(expr1, expr2; expr3)
/* body of loop */
Now, conventionally, expr1 is the loop initialization, and expr2 is the condition under which to keep going, and expr3 is the increment between loops. But that's only a convention -- in actuality, the compiler just arranges to execute expr1 once, then expr2 to decide whether to take another trip through the loop or not, then expr3 at the bottom of the loop. So it's more or less equivalent to
expr1;
while(expr2) {
/* body of loop */
expr3;
}
Or, stated another way:
expr1;
while(1) {
if(!expr2) break;
/* body of loop */
expr3;
}
But then the other key point is that, yes, the expression
i = -1
doesn't look much like a condition; it looks like an assignment. But in C, when you use an expression as a condition (that is, in a context where what we care about is whether the expression is "false" or "true", all we really care about is whether the expression evaluates to zero or to non-zero. And the value of an assignment expression is simply the value that was assigned. So the value of
i = -1
is -1, and that's not zero, so it's interpreted as "true". So if you say
while(i = -1) {
/* body of loop */
}
the condition is always "true", so it will be an infinite loop, unless there's a break statement in the body somewhere (or a return, or a call to exit(), or something like that).
First for loop one does nothing and will be removed from the generated code if the optimisation is on
Second one enters the loop one time. The actual loop will be removed by the optimising compiler and replaced by the puts, initialisation and printf call.
https://godbolt.org/g/T5wgqt
printf with the format string only is replaced by the puts
This question already has answers here:
What does the comma operator , do?
(8 answers)
Closed 6 years ago.
Prog 1:
#include<stdio.h>
int main()
{
int i=0;
while(i<=8,i++);
printf("%d",i);
return 0;
}
Prog 2:
#include<stdio.h>
int main()
{
int i=0;
while(i++,i<=8);
printf("%d",i);
return 0;
}
The output of Prog 1 is 1 and that of Prog 2 is 9.
Can someone explain whats going here. How the two codes are different?
The comma operator evaluates both of its arguments in turn, throwing away the result, except for the last. The last evaluated expression determines the result of the entire expression.
i<=8,i++ - here the value of the expression is the value of i++, which is the value of i before being incremented. It's 0 so the loop immediately terminates.
i++,i<=8 - here the value of the expression is the value of i<=8 which is 0 only when i is incremented to 9.
On a personal note: I think the second form, while somewhat comparable to a for loop, is less clear to the reader of the code than an actual for loop.
1 while ( condition )
2 statement;
3 more_code();
In the above code snippet, the statement can be executed repeatedly as long as condition is true. On each iteration of the while loop, condition is evaluated to either true or false. If it's false, the while loop ends and execution continues beyond it's scope (in this case, line 4 with more_code().
We are usually accustomed to enclosing parts of code that we want to be executed in loop with curly brackets { and }, but that is not mandatory. If we do not do so, the looping code will consist of single statement, the one immediately following the while part.
It could actually be argued that the more common situation, where we combine while with curly brackets enclosed block of code could be interpreted as providing this block of code in place of a single statement, with braces providing information that the block should be treated (by compiler analysing it's relation with preceding and following code) as if it was a single statement.
However, as it is perfectly valid to provide a single statement, not a usual block of code, it's worth to understand that there is a valid statement that is empty. We get an empty statement by typing a semicolon without preceding it with a code causing anything. So following is perfectly valid:
1 code;
2 ; // empty statement
3 ; // another empty statement
or in fact this:
1 code;; // a "code" statement followed by empty statement in the same line
The while( condition ) part is not terminated with a semicolon, so if it's supposed to control some actual code (apart from condition), it should not be followed by a semicolon. If it is immediately followed by a semicolon, that semicolon will constitute (and be so interpreted by compiler) an empty statement, so the looping code will be empty. If that's unintended, then the code we wanted to be looped, whether a block of code or a statement, will not be looped, but rather executed once, after (and if) loop ends.
1 int a = 0;
2 while ( a < 3 ) ; // Next line is not part of loop - only the empty statement this semicolon creates is. This loop is infinite, or in other words it will never end.
3 a++; // This won't be executed even once.
4 printf("This never happens.");
(It's worth realizing that lines are only important for us, humans, in C. Lines and indentation can be misleading if they represent the intentions of programmer, when he failed to write the code functioning as he wanted it to.)
Therefore what happens in both snippets from the question, is we get condition evaluated continuously until it yields false. To understand what's going on we need to examine the way comma operator works.
(Note, while comma as a character can be used with a completely different meaning in various places in C - I can think of function declarations, definitions and calls - in this case comma character is part of condition, therefore it acts as an operator - something akin to + or % operators.)
expression1 , expression2
Comma operator causes expression1 to be evaluated first, then expression2, and returns the value of expression2.
Upon every evaluation of condition, we will thus evaluate both expressions, (in this case both being operands, i++ and i<=8), then consider value of the right one as result of comma operand itself, and thus as value of our condition. So the loop will keep repeating as long as the right operand resolves as true.
While usually we use condition to control the execution of loop, often, as in this case, condition may have "side" effects (intentional or unintended). In our case variable i is affected by every evaluation of condition: it is increased by one.
Our example differs only in order of operands of condition, therefore pay attention to the right operand which really controls the execution of the loop.
Let's examine the second example first. In this case we have condition i++, i<=8. This means upon every evaluation we first increase i, then check if it's less than or equal to 8. So on first evaluation of condition we will increase i from 0 to 1 and conclude that 1<=8, so the loop continues. The loop so constructed will break when i becomes 9, ie. on the 9th iteration.
Now as for the first example, the condition is i<=8, ++i. Since comparison has no side effects, that is we could perform any number of comparisons in any order and if that's the only thing we did, that is if we did not perform any other action in a way or order dependent of results of the comparisons, those comparisons would do absolutely nothing. As is in our case, we evaluate i<=8 which evaluates to true or false, but we make no use of this result, just proceed to evaluating the right operand. So left operand absolutely doesn't matter. Right operand, on the other hand, has both a side effect and it's value becomes value of entire condition. Before each loop iteration we check if i++ evaluates to true or false.
i++ is a unary operator of post-incrementation. It returns value of i then increases it by one (the difference between i++ and ++i is subtle but crucial in cases like this one). So what happens is we first check whether i is true or false, then i is increased by one.
In C there is no boolean type. Integers are considered to be true if they have a non-zero value.
So upon first evaluation of i++ we get 0, that is false. This means the loop is broken without even a single iteration. However it does not break evaluation of i++, which causes i to increase by one before we're done with the loop and execution proceeds beyond it. So once we're done with the while loop, i is already 1.
If we want to be very precise in our understanding, the part where we take the result of evaluating entire condition happens, chronologically, after we are finished executing any code involved in this evaluation. So we first memorize that i was 0 at the point we got toward i++ part, then we increase i by one, and then we are finished executing condition, so we provide value of 0 to the code that decides if we should do another (in this case first) iteration or jump beyond looping part and move on. This is exact reason why everything within condition will actually happen even though the fact that loop will end was already determined: it was determined, but it was not checked and acted upon until condition finishes executing.
The expression separator operator , forces evaluation from left to right, and is also a sequencing point.
Prog 1: consider i <= 8, i++. i <= 8 is evaluated and discarded then i++ is evaluated. The entire expression has the unincremented value of i. Since i is initially 0, the while loop terminates on the first iteration. The output will be that singly incremented value of i, i.e. 1.
Prog 2: i++ is evaluated and the result discarded, then i <= 8 is evaluated with the new value of i since , is a sequencing point. So the while loop runs until i <= 8 is no longer true with the incremented value of i. The output will be 9.