Today I made a typo, and then found below code can be compiled successfully:
#include <stdio.h>
int main()
{
int i;
for (i=0;1,2,3,4,5;i++)
printf("%d\n", i);
}
I don't understand why
1,2,3,4,5
can be treated as a condition?
Today I made a typo, and then found below code can be compiled successfully:
#include <stdio.h>
int main()
{
int i;
for (i=0;1,2,3,4,5;i++)
printf("%d\n", i);
}
I don't understand why
1,2,3,4,5
can be treated as a condition?
Your for
condition is the expression 1,2,3,4,5
. This expression is evaluated using C's comma operator and yields 5
. The value 5
is a valid boolean expression that is true, therefore resulting in an infinite loop.
You are using the comma operator. The value of 1, 2, 3, 4, 5
is 5.
More generally, the value of a, b
is b
. Also, the value of f(), g()
is the return value of g()
, but both subexpressions f()
and g()
are evaluated, so both functions are called.
Yes. As others say it's .always true and the comma operator yields 5, hence the loop will repeat infinite times
You can verify it by replacing 5 with 0 . Like this 1,2,3,4,0
Here 0 is false, hence the condition fails.
Yes, 1,2,3,4,5
can be treated as a condition.
The output of 1,2,3,4,5
is 5.
In fact, you need not specify any condition in for
loop.
for(;;)
is a valid syntax.
A for
loop:
for( E1; E2; E3 )
IB
with expressions E1, E2, E3 and an instruction IB is equivalent to a while
loop:
E1;
while( E2 )
{
IB;
E3;
}
The only exception is E2, which must be present in while
loop condition whilst may be omitted in a for
loop condition (and then it is considered equal 1).
So, as others already said, your 1,2,3,4,5
is a comma expression equivalent to a constant 5
, making the loop looping infinitely.
See that this code runs... but the for loop continues indefinitely. The condition 1,2,3,4,5 is always verified. The compiler accepts more that one conditions in for loops. For example:
for(i=0, j=0; i<X, j>y; i++, j--)
//.....
So 1,2,3,4,5 are five conditions (not one) and all these conditions are verified (in fact, these numbers are all different from 0 so they're always true).
// try to know the meaning of condition.
#include <stdio.h>
int main()
{
int i=0;
if(i<=5) // try this
{
printf("%d\n",i);
i++; // increment i
}
}