Because what you think is happening isn't.
The comparison is carried out left to right :
Result
z>=y 4>=4 1 (TRUE)
1>=x 1>=3 0 (FALSE)
hence the result of 0
shibblez
Junior Poster in Training
72 posts since Oct 2010
Reputation Points: 15
Solved Threads: 6
>>printf evaluation will be done right to left
I think you misunderstood the lecturer.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
>>,z>=y>=x
The evaluation is always left to right, not right to left. Z >= y, or 4 >= 4 is true, and 4 >= x or 4 >= 1 is false, so the result is 0.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
4>=1 is not true. So you get a 0.
4 >= 1 is false, so the result is 0.
Since when? Have they changed something since I've been in school?
WaltP
Posting Sage w/ dash of thyme
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
What is apparent is that there are differing views on what the evaluation. The solution is simple, if there is any ambiguity then use brackets.
shibblez
Junior Poster in Training
72 posts since Oct 2010
Reputation Points: 15
Solved Threads: 6
Since when? Have they changed something since I've been in school?
You are right, 4>=1 is true. But I think what is going on is that the program is comparing true (1) with the value of x, which is 3.
Z>=y is true (1)
1 >= x is false
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
What is apparent is that there are differing views on what the evaluation. The solution is simple, if there is any ambiguity then use brackets.
Doh!!!
#include <stdio.h>
int main()
{
int x=3;
int y=4;
int z=4;
printf(" z >= y >= x %d \n", z >= y >= x);
printf("(z >= y) >= x %d \n", (z >= y) >= x);
printf(" z >= (y >= x) %d \n", z >= (y >= x));
return 0;
}
Results:
z >= y >= x 0
(z >= y) >= x 0
z >= (y >= x) 1
So obviously left to right...
WaltP
Posting Sage w/ dash of thyme
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
Its always from left to right even if there are parentheses in the expression. The example you posted displays undefined behavior, meaning there is no consistent result among compilers.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
In the example posted, yes they are all undefined behavior. Here is more in-depth explanation.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343