How this for loop is working
int main(){
char i=0;
for(i<=5 && i>=-1; ++i ;i>0)
printf("%d \n",i);
printf("\n");
return 0;
}
How this for loop is working
int main(){
char i=0;
for(i<=5 && i>=-1; ++i ;i>0)
printf("%d \n",i);
printf("\n");
return 0;
}
Ahh thanks for the clarification.
Your asking why the for loop in your example is executing, even though the increment operand and loop condition have been swapped, and the fact that the variable is a char. Lets consider the proper structure of a for loop:
for (initialise variable; for condition; increment variable)
{
//Do stuff
}
The answer to your question is simple:
Lets name parts of the for loop:
for( Expr1; Expr2; Expr3 )
DoStuff;
This is how a for loop works:
1. It executes Expr1
first. in your loop does nothing in fact, since it doesn't check the result of this execution.
Then it executes Expr2
and treat it's result as a condition if it's 0
terminates the loop, if it's "not 0" go to step 3. In your loop this means that i
will be incremented, thus it's now 1, so result is true
.
Then it runs the DoStuff
part, in your case print out i value
Next it executes Expr3
, no check, just run it, in your case does nothing again, since it's a condition and its result isn't used.
Next it goes back to Expr2
executes it and check it's result. now i
is 2
, still a true
condition.
Again execute the DoStuff
part and go to step 4
The loop will stop once i
value changes back to 0
.
When? since it's type is char
, after reaching 127 it will overflow to -128 and then increment back to -1 and then 0. and stop.
Whenever you want to understand for loop in this kind of situation you can convert for loop into while to understand it.
The for syntax is:
for (initialization; condition; operation)
...
It can be converted into while as:
initialization; while (condition) { ... operation; }
So in your case
i <= 5 && i >= -1; // Initialization
while(++i) { //condition
printf("%d \n", i);
i > 0; // operation
}
Initialization part will be execute once it will check for condition.Here in your case it is ++i
so increment every time.Here i>0
means if i==0 then loop will stop it does not matter i
is positive or negative Thumb rule to remember in this kind of situation is if (i == 0 ) then true
else false. i>0
remains true)in every case after that so loop is infinite.
To understand for loop best answer I have seen in SO is this
There's not rule about the order of for loop condition and increment operation, the latter even don't need to be an increment operation. What it's expected to do is determined by you. The code is just same as the following semantically.
char i = 0;
i <= 5 && i >= -1; // Run before the loop and only once. No real effect here.
while (++i) { // Condition used to determine the loop should continue or break
printf("%d \n", i);
i > 0; // Run every time inside the loop. No real effect here.
}
BTW: It'll be an infinite loop (because ++i
is a nonzero value until overflow).