Win a copy of Fixing your Scrum this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Rob Spoor
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Holloway
  • Piet Souris
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Frits Walraven
  • Himai Minh

Postfix operation

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


This is one of Dans' question. The answer is 5 as per ( a=1+2+2).
My doubt is what happened to the postfix operation a++. ( Is it not correct that this postfix makes a as 6.
 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Vidyavathi saravanan:


This is one of Dans' question. The answer is 5 as per ( a=1+2+2).
My doubt is what happened to the postfix operation a++. ( Is it not correct that this postfix makes a as 6.



The way I got to the answer was as follows:
int a=1;a += ++a + a++;
then: a += (2) + a++;
then: a += (2) + (2); ->a will be incremented to 3 once the statement is finished
then: 1 += (2) + (2);
equals: a=5 (assign 5 to the value of a)

Remember that the postfix operator only takes effect AFTER the statement is processed and as such, is not involved in the calculation of this line. Since the value of a has already been set to 5, the effect is that the value of a is incrmented but it is not assigned to a and basically is lost.

Think of it this way:
We have already assigned the value of the variable a so you can increment it, but it will be ignored as the assignment is already done.
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What actually happens is the following:

a += ++a + a++; (a==1)
a = a + ++a + a++; (a==1)
a = 1 + ++a + a++; (a==1)
a = 1 + a + a++; (a==2)
a = 1 + 2 + a++; (a==2)
a = 3 + a++; (a==2)
a = 3 + 2 [need to increment a now]; (a==2)
a = 3 + 2; (a==3)
a = 5; (a==3)
(a==5)

That is, a does get incremented, but before the assignment of the expressions value happens.

Does that help?
 
Sometimes you feel like a nut. Sometimes you feel like a tiny ad.
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic