Why does the below program gives me the opposite answer after comparison operations are done?
main()
{
int k=35;
printf("%d\n%d\n%d",k==35,k=50,k<40);
}
output
0 50 1
Why does the below program gives me the opposite answer after comparison operations are done?
main()
{
int k=35;
printf("%d\n%d\n%d",k==35,k=50,k<40);
}
output
0 50 1
This program is not a valid C program as per the C standard.
There are 2 problems associated with this program.
Problem 1: Unspecified Behavior
The order of evaluation of arguments to a function is Unspecified[Ref 1].
Problem 2: Undefined Behavior
This has undefined behavior[Ref 2] because a variable should not be modified more than once without a intervening sequence point. Note that ,
in the function arguments does not introduce a sequence point. Thus k
gets modified without a intervening sequence point and causes Undefined Behavior.
So you cannot rely on the behavior to be anything specific in this case. The program is not a valid C program.
[Ref 1]
C99 Standard 6.5.2.2.10:
The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.
[Ref 2]
C99 Standard 6.5.2:
Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored.
Note that Unspecified and Undefined Behavior are terms defined by the standard as:
C99 Standard 3.19 Unspecified Behavior:
behavior where this International Standard provides two or more possibilities and imposes no requirements on which is chosen in any instance
C99 Standard 3.18 Undefined Behavior:
behavior, upon use of a nonportable or erroneous program construct, of erroneous data, or of indeterminately valued objects, for which this International Standard imposes no requirements
Did you notice that the second argument to printf is k=50? This is an undefined behavior because the order of evaluation of the parameters is unspecified
The order of evaluation of function arguments is not defined by the C standard. See C99 §6.5.2.2p10:
The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.
This means that each of the comparison k==35
, the assignment k=50
, and the test k<40
can happen in any order. When I tried your program using MSVC, the assignment happened first. Other compilers, or even other invocations of the same compiler, may choose different orders.
I wish you'd shown your output. However, my suspicion is that the problem is that you've included an assignment as one of the arguments to printf(), and heavens knows what order the three arguments were evaluated, i.e. k might have been 50 when the k==35 was evaluated ;-)