Whats the difference between:
int i;
for( i=0;i<5 && i<3;i++)
{
printf("stackoverflow.com");
}
and
int i;
for( i=0;i<5 , i<3;i++)
{
printf("stackoverflow.com");
}
I mean use of && instead of ','
Regards
Whats the difference between:
int i;
for( i=0;i<5 && i<3;i++)
{
printf("stackoverflow.com");
}
and
int i;
for( i=0;i<5 , i<3;i++)
{
printf("stackoverflow.com");
}
I mean use of && instead of ','
Regards
In the second code block, only i < 3
is actually used to evaluate whether the loop should exit. The i < 5
expression is evaluated, but its value is discarded. See the comma operator for more info.
There is functionally no difference between your examples because i < 3
is the limiting expression and appears second. Both loops will exit when i reaches 3. However, if you switched the terms so that you have i < 3, i < 5
, then the second kicks out when it reaches 5 because only the value of i < 5
is considered.
When using the comma operator ,
in a statement like the:
( <expression1>, <expression2> )
the <expression1>
is evaluated and discarded, then the <expression2>
is evaluated and its value is returned. In summary the right most expression is evaluated and its value returned. Other expressions are evaluated and discarded. So your statement of:
for(i=0; i<5 , i<3; i++)
is equivalent to:
for(i=0; i<3; i++)
As for the first statement, this expression:
(i<5 && i<3)
is a simple AND boolean evaluation. A funny one because it is enough to say:
(i<3)
Long story short, who ever made this example probably expects you to say "both conditions evaluate to second expression".
In this case they will do exactly the same.
The thing that differs is that in the first case i<3
will not be evaluated every time. A statement on the form A && B
will only execute B
if the return value of A
is true
. The reason is that the logical value of &&
is true if both operands are true. If one of them are false, the whole expression is false, so if the left operand evaluates to false, there's no need to evaluate the right operand.
The comma operator on the other hand evaluates both operands, but the result of the left operand is discarded.