I am experimenting about what can be put into a for loop declaration in C and how it can be used. I tried the following:
#include <stdio.h>
int stupid(int a)
{
if(a == 3)
return 1;
else
return 3;
}
int main(void)
{
int i, j;
for(i=0; stupid(i)==3,i<10; i++)
printf("%d\n", i);
return 0;
}
When I run the program it just prints the number from 1 to 10, and if I use &&
instead of comma between the stupid(i)==3
and i<10
, then the program just prints the numbers up to 3. Why?
I don't really understand how this works and I was expecting the loop to pass all numbers and "skip" 3, but continue up to 10 and that's not really happening. Why does this happen? Is there some site where this is more clearly explained?
The second clause in the for loop (in your case stupid(i)==3,i<10
) is a conditional that is evaluated prior to each entry of the loop body. If it evaluates to true
then the loop body is executed. If it evaluates to false
then the loop ends and execution continues after the loop body.
With the comma (stupid(i)==3,i<10
), the code evaluates stupid(i)==3
, forgets the result, and then evaluates i<10
, and uses that result for the loop condition. So you get the numbers from 0 to 9.
stupid(i)==3 && i<10
will evaluate to true
only if both parts of the expression are true, so when i=3
, stupid(i)==3
is false, and the loop exits.
The comma operator evaluates the part before the comma, discards the result, evaluates the part after the comma, and returns that. So in your for loop the part after the comma is i < 10 and this is what is returned as condition for the for loop. That is why it prints the numbers 1 to 10 if you have the comma operator in it.
If you put the &&
operator in it, it means that both conditions before and after the &&
have to be met. Otherwise the loop terminates. So if i == 3
the left part evaluates to false and your loop ends.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With