Reputation: 407
I have an infinite loop here, but why?
int end = 5;
for(int i = 0; i < end, printf("at condition i=%d\n",i); ++i)
{
printf("inside i=%d\n",i);
}
Upvotes: 2
Views: 217
Reputation: 9484
If compiled with -Wall
,
warning: left-hand operand of comma expression has no effect
So i < end
has no effect. printf()
return no.of characters it printed.
Based on return value(Non zero value here), infinite loop occurs.
Upvotes: 2
Reputation: 33533
The left operand of the comma operator is evaluated as a void expression, the evaluated result of a comma operator is the result of the right operand. So the "if" part of your for
loop looks at the result of the printf
, which is higher than zero, meaning it will never end.
You can fix it by swapping them:
int end = 5;
for(int i = 0; printf("at condition i=%d\n",i), i < end; ++i)
{
printf("inside i=%d\n",i);
}
But better is to not do this at all. It is not very readable.
Upvotes: 5
Reputation: 106092
You need to learn about comma operator. The result of comma expression is the result of right operand. In controlling expression i < end, printf("at condition i=%d\n",i)
, i < end
is evaluated and its result is discarded.
So, the loop is controlled by the value of the expression printf("at condition i=%d\n",i)
which returns number of characters that it prints and hence it evaluated always as true
here and results in an infinite loop.
Upvotes: 2
Reputation: 123558
In the expression i < end, printf("at condition i=%d\n")
, the comma operator causes the two expressions to be evaluated in sequence, but the result of the first expression is discarded, and only the result of printf
is used to control the loop. Since printf
will always return non-zero for that format string, the loop never terminates.
Use &&
instead:
for (int i = 0; i < end && printf("at condition i=%d\n"); i++)
Upvotes: 0
Reputation: 122453
The comma operator expression i < end, printf("at condition i=%d\n",i)
is used as condition. Its value is its right operand, which is the return value of printf
.
The return value of printf
is the number of characters it outputs, that's never zero in this case, so it's an infinite loop.
Upvotes: 3
Reputation: 4689
Because
1) i < end, printf("at condition i=%d\n",i)
returns the same value as printf("at condition i=%d\n",i)
.
2) printf()
returns number of printed characters (it is not zero in this case)
So condition in your loop is always true.
Upvotes: 1