1

I thought the relational operator == returns 0 when the statement to be checked is false and 1 when it is true. However, this is not what I am getting as output in a segment of code. Can anyone please explain?

I have tried looking up the internet for this but everywhere I have found the same explanation that I know.

int main()
{
    int x=35;

    printf("\n%d %d %d",x==35,x=50,x>40);

    return 0;
}

I expected the output to be: 1 50 1 But the output showed is: 0 50 0

  • 4
    What you are expecting is unspecified behavior. The order in which printf performs the operations is not standard. – Irelia May 19 '19 at 20:21
  • 1
    Possible duplicate of [Why are these constructs using pre and post-increment undefined behavior?](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior) – Deduplicator May 19 '19 at 20:46
  • 1
    Do not vote to close this. It's not a dupe and it's not a simple typgraphical error. – klutt May 19 '19 at 21:05

2 Answers2

6

The behavior of code that has both x == 35 and x = 50 in the arguments to a function is not defined by the C standard, because it both modifies x and separately uses its value, and the rules of C does not say which happens first. C 2018 6.5 2 says:

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

In x = 50, the main value is 50, and the side effect is to change the value stored in x to 50.

In x == 35, the expression is a value computation that uses the value of x.

In general, evaluations of subexpressions are unsequenced, because C 2018 6.5 3 says:

Except as specified later, side effects and value computations of subexpressions are unsequenced

C 2018 6.5.2.2 specifies what happens with function calls, and it does not specify the order in which arguments are evaluated. So 6.5 3, quoted above, applies. x = 50 and x == 35 are unsequenced. So there is both a side effect on x and a value computation of x that are unsequenced, so 6.5 2 applies, and the behavior is not defined by the C standard.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
1

The statement:

printf("\n%d %d %d",x==35,x=50,x>40);

modifies x such that (in this case) when the test x==35 is performed, x is equal to 50.

The order of evaluation of function parameters is undefined, so in other cases results may differ. Such code should be avoided. Consider:

printf( "\n%d", x == 35 ) ;
printf( "%d", x = 50 ) ;
printf( "%d", x > 40 ) ;

which is well defined and will produce the result you expected.

Note that the language defines zero and non-zero as representing false and true respectively rather than zero and one specifically.

Clifford
  • 88,407
  • 13
  • 85
  • 165