2
main()
{
   int k=35;
   printf("%d %d %d",k==35,k=50,k>40);
}

The output of this code is 0 50 and 0 I couldn't understand why? Because I have learnt that priority of assignment operator is the least and the releational operator priority is more that that then how this kind of output has come please explain?

  • ⟼Remember, it's always important, *especially* when learning and asking questions on Stack Overflow, to keep your code as organized as possible. [Consistent indentation](https://en.wikipedia.org/wiki/Indentation_style) helps communicate structure and, importantly, intent, which helps us navigate quickly to the root of the problem without spending a lot of time trying to decode what's going on. – tadman Apr 26 '21 at 03:13
  • 1
    Hint: The order in which the arguments are evaluated is not required to be in any particular order. – tadman Apr 26 '21 at 03:14
  • related/dupe: https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior – NathanOliver Apr 26 '21 at 03:20
  • Precedence is for disambiguation. There's no ambiguity between the assignment and relational operators here. If you had something like `k = 50 == 35`, that would be up to precedence to make it either `(k = 50) == 35` or `k = (50 == 35)`. – chris Apr 26 '21 at 03:23
  • Does this answer your question? [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) – Nate Eldredge Apr 26 '21 at 04:52

1 Answers1

1

There is no fixed order defined by the C standard. A compiler may choose to evaluate either left-to-right or right-to-left. So in your case, the compiler is evaluating the expression from right to left. And as you know that == generates the output as a boolean value. So the first evaluation done by the compiler is 35>40 which is False(0) and k=50 so simply assignment is done and finally, k(50) is compared with 35 which results in False(0).

Therefore your output is 0 50 0.

I hope it cleared your doubt..

Abhishek Jaiswal
  • 288
  • 2
  • 14
  • Left-to-right and right-to-left are not the only options for argument evaluation order. Further, they do not have to be in order at all; a compiler may interleave parts of the argument expressions. And the assignment part of an assignment expression is a side effect that may occur at a different time from the evaluation of the assignment expression. – Eric Postpischil Apr 26 '21 at 06:33