0
  • C program

    int i=1;
    
    printf("%d %d %d",++i, i++, ++i);
    

I am completely surprised about the output.

The Output of the above program:-

4 2 4

I know they saved values in the stack and then print the values on the console(i.e right to left execution)

If I follow right to left execution, it must print the following output

4 2 2
  • C++ program

Same happened with "C++";

int i=1;

cout<<++i<<i++<++i;

It also produces the same O/p as in the "C" program

 4 2 4

Will anyone know by which logic the values are printing in the console ?

VIKAS KOHLI
  • 8,164
  • 4
  • 50
  • 61
  • Short answer: Your expectations are wrong. Pre and post-increment operators do not always behave as you expect. *Be careful*. – tadman May 01 '17 at 05:42
  • 3
    The order in which function arguments are evaluated is undefined. – Jeroen3 May 01 '17 at 05:51
  • An explanation for this could be: (going from right to left) (a) ++i increments i to 2, and sets the address of i which has value 2 for the printf function to use (b) i++ increments the value to 3, but copies the value of old address of i for printf to use (note that this will never change from 2) (c) again ++i increments the value to 4, and sets the address of i for printf to use. After all this parameter evaluations the values at the addresses are coped and then passed to printf. I am not sure, this is exactly what happens but is just an hypotheses for it to make sense. – Ravi Upadhyay May 01 '17 at 06:06
  • But as @Jeroen3 mentioned C language itself does not imply any ordering for the function evaluation (it may vary across compilers), so you should never use such code. – Ravi Upadhyay May 01 '17 at 06:07
  • 3
    How did this mega-dupe get an upvote? – ThingyWotsit May 01 '17 at 06:21
  • @ThingyWotsit _Three_ upvotes, if you see the upvote downvote distribution.... – Spikatrix May 01 '17 at 06:26
  • @ThingyWotsit, @n.m. It looks like a legitimate question. Me too, I would like to know why `cout<<++i< – Marian May 01 '17 at 07:23
  • 3
    @Marian it is a legitimate question.... well, it was a legitiamte question once, a long time ago. The following thousands of times it was posted on SO were just duplicates that the posters did not search for. This UB is the most duplicated nonsense ever posted on SO. At least the thousands of duplicate 'null pointer excepton' questions are founded on, (mostly), real code. 'I++ + ++i', and derivatives thereof like this, are just madness dreamed up by profs and TA's, and would never be written into real apps :( – ThingyWotsit May 01 '17 at 07:30

0 Answers0