programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

expression evaluation

mounika paruchuri
Greenhorn
Posts: 26
Consider the following expression:
i--%5>0
the question is
a : What is the result of the expression, assuming that the value of i is initially 10?
b : Modify the expression so that it has the same result but is easier for programmers to read.
when I evaluate the expression using precedence... I get true....
10--%5>0 //1
9%5>0 //2 as unary is higher in precedence than % and >
4>0 //3 as % has higher precedence
finally true...
but the answer is given as :
Answer: false,(i-- % 5) > 0
can somebody explain why it is 'false'......

Angela Margot
Ranch Hand
Posts: 80
The location of the unary operator determines when that operation takes place. If an operator is --x then it occurs before any other operation. If it is x-- then it occurs after the other operations.
So, if it were --i%5>0 then the result would be true because the unary operation would take place before the % - thus if i=10, --i%5>0 -> 9%5>0 -> 4>0 is true
But because it is i--%5>0 the i%5 takes place before the i-- . In this case if i=10, i--%5>0 -> 10%5>0 -> 0>0 is false and then i=9.
Help any?

Brian Lugo
Ranch Hand
Posts: 165
Monika,
Here is link to understanding post fix operators:
http://www.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=014701
Hope this helps,
Brian

mounika paruchuri
Greenhorn
Posts: 26
thanks Leilani for the great explanation and brian for the link....it did help.

Rob Ross
Bartender
Posts: 2205
arrrg. This is a good example of why tests are hard! I KNOW how postincrement/predecrement work, but that little fact got lost in my brain somewhere and when I first looked at this question, I used 9 for the left-hand side operator, giving 4 for the answer, making the statement true.
But of course this is wrong, because I should have used 10. I know this, yet it slipped my mind.
That's why it's critical to go slow, take your time, and concentrate on the details of each question so you don't make silly mistakes like I just did!
[ February 20, 2002: Message edited by: Rob Ross ]