Program code :
int main()
{
int i;
for (i = 0; i < 0, 5; i++)
printf("%d ", i);
return 0;
}
The loop above is executed infinite times.
What does i<0,5
mean, and how it is evaluated?
Program code :
int main()
{
int i;
for (i = 0; i < 0, 5; i++)
printf("%d ", i);
return 0;
}
The loop above is executed infinite times.
What does i<0,5
mean, and how it is evaluated?
Based on operator precedence, this is interpreted as (i < 0), 5
. The comma operator evaluates all statements, but discards their values except the last. So for practical purposes the loop reads as
for (int i = 0; 5; ++i) {...}
Because a non-zero value is interpreted as true
in C/C++, this is equivalent to:
for (int i = 0; true; ++i) {...}
which is an infinite loop.
why
i<0,5
how it is evaluated?
Because the value of a comma expression is its last value. The values in this comma expression arei < 0
and 5
. This first is evaluated to false
and thrown away! The second (and last) is 5
which is true
. That is used as the for
loop condition expression.
A for
loop runs until its condition expression is false
, so this loop run forever.
It is very easy to check yourself. Try:
int main()
{
int i, y;
for (i = 0; i < 0, 5; i++)
{
y = (i < 0, 5);
printf("%d ", y);
}
return 0;
}
And you know that second expression in your list is the value of the comma expression.
In the condition of the loop there is used the comma operator
for (i = 0; i < 0, 5; i++)
printf("%d ", i);
From the C Standard (6.5.17 Comma operator)
2 The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value
So this expression with the comma operator
i < 0, 5
has two operands and can be rewritten for clarity like
( i < 0 ), ( 5 )
So the value of the expression according to the quote from the C Standard is the value of the second operand that is 5
.
As 5 is not equal to 0 then the condition always evaluates to logical true and you have an infinite loop.
From the C Standard (6.8.5 Iteration statements)
4 An iteration statement causes a statement called the loop body to be executed repeatedly until the controlling expression compares equal to 0. The repetition occurs regardless of whether the loop body is entered from the iteration statement or by a jump.155