Win a copy of TDD for a Shopping Website LiveProject this week in the Testing 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Need help with a++/b-- expression

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
HI,

Can someone pls help me with this.
int a =8;
int b=3;
float f = (float)a++/b--;

correct ans is 2.66 and not 4.5. As per the operator precedence ++ and -- shd be evaluted first the / ?

Thanks,
Sarika.
 
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
Sarikaa Bhatnagar
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
HI,

my ques is why ++ and -- are not evaluated first when as per operator precedence rule ++ adn -- takes precedence over / operator. So why the division happend 8/3 and not 9/2

thanks,
sarika.
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


So why the division happend 8/3 and not 9/2


Because you are using the postfix increment operator, the variable is used in the expression then incremented.. Try the prefix version i.e ++a
 
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Sarikaa Bhatnagar:
HI,

my ques is why ++ and -- are not evaluated first when as per operator precedence rule ++ adn -- takes precedence over / operator. So why the division happend 8/3 and not 9/2

thanks,
sarika.



The ++ and -- are evaluated first but the value of a++ is 8 and value of b-- is 3.

The value of x++ is the old value of x.
 
Seriously? That's what you're going with? I prefer this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic