0

Unable to understand the order of compilation of printf in this program

I thought the output will be 4 2 2 0,since printf executes from right to left.

   #include<stdio.h>
    using namespace std;

    main()
    {   int x=0;
    printf("%d %d %d %d",++x,x++,++x,x++);
     }

Expected 4 2 2 0 Actual 4 2 4 0

Ajay Sabarish
  • 171
  • 2
  • 6
  • 5
    "printf executes from right to left" This is incorrect. You don't choose the order in which the parameters are evaluated, and your code contains undefined behaviour. You aren't allowed to do what you're doing. – Thomas Jager May 10 '19 at 17:43
  • Try it with a different compiler. Try it with different levels of optimization. Be amazed. – tadman May 10 '19 at 17:45
  • 2
    @ThomasJager: Re “You aren't allowed to do what you're doing.” They are allowed. There is no rule against it. People should not mistake the lack of a definition by the C standard as a prohibition. – Eric Postpischil May 10 '19 at 17:58
  • @ThomasJager Can you please elaborate? I though printf and cout work by pushing the terms into the stack. And why isn't this code allowed? – Ajay Sabarish May 11 '19 at 18:24
  • @tadman What is the reason for this inconsistency,and by the way what is happening? – Ajay Sabarish May 11 '19 at 18:25
  • @AjaySabarish That is the way that the arguments passed in, but you don't know what those values are. The standard doesn't specify, so the compiler is free to generate whatever code it chooses. Your question was marked as a duplicate of an existing question, please see that one. – Thomas Jager May 11 '19 at 19:24
  • It's because there's no requirement for these to be evaluated in any particular order. The compiler has significant latitude here. If it's not nailed down in the language specification, it's *undefined behaviour* which means you can't depend on it. In this case you should never assume a particular order of evaluation as there is no guarantee it will be in any particular order. So you *can* write code like this and after that line `x` will be in a predictable state, but the intermediate states are somewhat muddled. – tadman May 13 '19 at 15:53

0 Answers0