-5

Given the following code:

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

why the result is (3,a=3,a+b=5)

enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
Ack
  • 3
  • 3
  • for another example: int arr[] = { 6, 7, 8, 9, 10 }; int *ptr = arr; *ptr += 3; printf("(%d,%d,%d)", *ptr, *ptr++, *(ptr++)); the result is (8,7,9) – Ack Aug 03 '15 at 11:42
  • @The Paramagnetic Croissant, haccks I don't think this question is duplicate – Ack Aug 03 '15 at 12:12
  • @Martin James I saw this code from a book or an article maybe, and confused about this bad code, I will never create those codes by myself. – Ack Aug 03 '15 at 12:16

1 Answers1

0

You are printing the result of an assignment (a=a+3) which is the assigned value (3). But the evaluation order of the parameters depends on the compiler (undefined behaviour). it could print:

(3,a=3,a+b=5)

or:

(3,a=0,a+b=2)

or even:

(3,a=0,a+b=5)
enrico.bacis
  • 30,497
  • 10
  • 86
  • 115