Before I answer this, I should say that you should generally AVOID such code while actual programming, because it is confusing.
Anything which makes the result not obvious, should be avoided.
To answer the question, the result you see is because of operator precedence in C. The unary ++ operator has precedence over the binary + operator. So first ++a is done, then again another ++a is done. Then a + a is done with the final value of a, which is 12.
Reason for Output : 24
as ++ having higher priority than + operation first both ++ will be executed so even before performing + Operation value of a will be 12.
Above is true for 2 Operand and One Operator at a time.
printf("%d",a=++a + ++a + ++a);
13 12 12
OUTPUT = 37
as first two ++a will make 24 and then ++a will be taken in operation so 13 will be added so output will be 37
printf("%d",a=++a + ++a + ++a + ++a);
14 13 12 12 = 51
The answer will depend on the compiler implementation, so its best to avoid such code as it produces ununderstandable and unpredictable results.
Hi increment operator is evaluated in printf as Right to left. So first RHS ++a is evaluated and the value becomes 11. Then the previous one is evaluated and the value becomes 12. Now current value of a is 12. so RHS ++a + ++a will produce the output 24. Now the LHS ++a will make the value of a as 13. so the now ++a+(++a + ++a) becomes 37.
Thank you all for the answers. These tricky questions were asked while solving placement apti questions for students.
Then please let me know how postfix works. Is there any generic rule that will be followed for postfix and prefixa=10;
printf("%d",a=a++ + a++); // a is 21
printf("%d",a); // a is 21
printf("%d",c=a++ + a++); // c is 21
printf("%d",a); // a is 12. Please let me know when 'a' value is updated and why it is not reflected anywhere in the previous code..