-3
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
    int i = 2;
    printf("%d %d\n", ++i, ++i);
    i = 2;
    printf("%d %d\n", i++, i++);
    return 0;
}

Output:

4 4

3 2

I know that arguments are passed from right to left in printf(). But if I'm getting a 3 2 in the second line, why don't I get a 4 3 in the first line?

user2684198
  • 812
  • 1
  • 10
  • 18

3 Answers3

7

It is a undefined behavior.

printf("%d %d\n", ++i, ++i);

i is modified more than once in the above statement.

Community
  • 1
  • 1
Balu
  • 2,247
  • 1
  • 18
  • 23
1

The code you have written comes under Undefined behavior of programming languages.Because the parser of language on each platform could be a different one.Some parser read from left to right and vice-versa.See the wiki link for complete information

Ankur
  • 3,584
  • 1
  • 24
  • 32
0

You can consider this case with the example of a stack i.e FILO.

In the second printf statement printf("%d %d\n", ++i, ++i);

both ++i will go to the stack one after the other, left to right. since its post-increment, the values that go will be 2 and 2 but while coming out the first value will be 2 and the second value will be 3.

Sid
  • 21
  • 1
  • 8