0

When I code in C programming, I write:

a = 2;
printf("%d %d", ++a, a);

and

a = 2;
printf("%d %d", ++a, a + 1);

as similar output

3 3

But When I swap them, they have diffrent:

a = 2;
printf("%d %d", a, ++a);
3 3

and

a = 2;
printf("%d %d", a+1, ++a);
4 3

why has different output?

noname
  • 21
  • 1
  • 3
  • Because it's not specified how `printf()` handles the arguments! It's unspecified behavior! – Rizier123 Nov 23 '14 at 05:49
  • why a + 1 and a have the same output??? – noname Nov 23 '14 at 05:52
  • Because it's not specified what printf handles first! So it could be that the second argument is first and 2+1 is output 3 (without an assignment to a) and then argument one is handled and 2 increment is also 3! – Rizier123 Nov 23 '14 at 05:55

1 Answers1

0
printf("%d %d", a, ++a);

This leads to undefined behavior. It depends on how printf() processes the arguements.

Gopi
  • 19,784
  • 4
  • 24
  • 36