-6

Can anyone please explain me the correct logic behind the output for following code.

 #include <stdio.h>
 int main()
    {
            int a=1;
            printf("%d\t%d\t%d\n",a,a++,++a);
            return 0;
   }

Expected output is 3 2 3

  • 1
    The output is: `UB` The evaluation of the parameters is unspecified! (This question was asked asked so many times before) – Rizier123 Feb 05 '15 at 13:00
  • The output is undefined behavior – karthikr Feb 05 '15 at 13:01
  • @Rizier123 In c evaluation of parameters is from right to left here. – Austin Philip D Silva Feb 05 '15 at 13:02
  • @Rizier123: The evaluation is undefined, not unspecified (which is even worse --- there are some subtle differences). – Tim Čas Feb 05 '15 at 13:03
  • 2
    @AustinPhilipD'silva,@Rizier123: No, evaluation of parameters is undefined here. See C99 standard, 6.5p2 and 6.5.2.2p10. – Tim Čas Feb 05 '15 at 13:05
  • 3
    @AustinPhilipD'silva: C does ***not*** specify the evaluation of parameters being R-to-L. In many implementations, it is R-to-L because that makes it easier to manage the stack. But this is not required nor guaranteed. – abelenky Feb 05 '15 at 13:05

1 Answers1

3

Your code is undefined behavior, so there is no such thing as "correct logic" for it --- it could output 0 0 0, 1 1 2, hello, world, or emit nasal demons.

From C99 standard:

  • Section 6.5, paragraph 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 read only to determine the value to be stored.

  • Section 6.5.2.2, paragraph 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.

Tim Čas
  • 10,501
  • 3
  • 26
  • 32
  • i got the answer as 3 2 3!!!. – Austin Philip D Silva Feb 05 '15 at 13:05
  • As far as i remember In C calling convention is from right to left for printf. – Austin Philip D Silva Feb 05 '15 at 13:07
  • @AustinPhilipD'silva: Also, if it were right-to-left, you should've gotten `3 2 2`. Because you'd first evaluate the `++a`to `2`, then `a++` to `2` (but incrementing it to `3` in the process), and *then* `a` to `3`. – Tim Čas Feb 05 '15 at 13:13
  • 1
    @Rizier123: 6.5p2 makes it undefined. In case you're wondering, `undefined` means "illegal, compiler vendor doesn't have to handle errors in any way", and `unspecified` means "compiler vendor must choose a way (out of a set of choices), but *does not* have to document what they've picked". You also have `implementation-defined`, which is similar, but the choice *must* be documented. – Tim Čas Feb 05 '15 at 13:16