Reputation: 33
int x = 15 ;
printf ( "\n%d \t %d \t %d", x != 15, x = 20, x < 30 ) ;
The output of the code is 1 20 1 but I assume it should be 0 20 1 since 15 == 15...
I am facing a problem with the "x != 15" part
Upvotes: 3
Views: 342
Reputation: 108978
Your code suffers from unspecified behaviour: the order in which the expressions are executed is not mandated by the Standard to be left-to-right. Try this instead
int x = 15 ;
int result1 = (x != 15);
int result2 = (x = 20);
int result3 = (x < 30);
printf ( "\n%d \t %d \t %d", result1, result2, result3 ) ;
Upvotes: 0
Reputation: 70909
In my experience, most lists of arguments are processed from the right to the left under most C / C++ compilers, even though the specification makes no statement about the required order of evaluation.
With such an understanding of how many compilers work, your list of arguments would be evaluated like so
printf ( "\n%d \t %d \t %d", x != 15, x = 20, x < 30 ) ;
evaluates (possibly) in the order of
x < 30 => 1
x = 20 (assigns x to 20, returning 20) => 20
x != 15 => 1 (because x is now 20)
If this evaluation order holds for your compiler, then rearranging the arguments like so
printf ( "\n%d \t %d \t %d", x < 30, x = 20, x != 15 ) ;
should yeild
1 20 0
because the comparison x != 15
will occur before x
is reassigned to 20.
The lesson of this exercise is to generally avoid assignments in list constructs (things that look like "a, b, c, d") or at least not to read assigned variables within the same list construct, as you cannot be assured of right to left or left to right evaluation (it's compiler dependent).
Upvotes: 5
Reputation: 59607
You're assigning a new value to x with x = 20
.
You can't assume any specific order to these operations in the argument list to a function call.
Upvotes: 7