saving . . . saved Post increment has been deleted. Post increment has been hidden .
Post increment
Title
Question
a=10;
printf("%d",a=++a + ++a);

For the above code snippet, am getting the answer as 24 for 'a'. According to my understanding, the output is 23.
Kindly explain this

C-and-Cpp General None min None sec 29-02-20, 11:34 a.m. gayathrisadasivam

Answers:

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.

29-02-20, 11:54 a.m. bhaskar76
No Sir its not 100% true then according to your answer following code output should be 39 but it gives 37.
a=10;
printf("%d",a=++a + ++a + ++a);
13 12 12
OUTPUT = 37

29-02-20, 12:06 p.m. kapilshukla2006

Login to add comment


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.

a=10;
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

a=10;
printf("%d",a=++a + ++a + ++a + ++a);
14 13 12 12 = 51


29-02-20, noon kapilshukla2006


The answer will depend on the compiler implementation, so its best to avoid such code as it produces ununderstandable and unpredictable results.
29-02-20, 2:53 p.m. bhaskar76


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.
29-02-20, 4:11 p.m. gsivakamasundari


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 prefix
a=10;
printf("%d",a=a++ + a++);       // a is 21
printf("%d",a);                         // a is 21


a=10;
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..
02-03-20, 10:01 a.m. gayathrisadasivam


Log-in to answer to this question.