Link to home
Start Free TrialLog in
Avatar of shahrine99
shahrine99

asked on

expression

here is the following statement

i = 5;
j = i++ - ++i;

What are the possible values of j in Java?

My guess would be 0 because if I increase i then subtract i then i should get 0, am I right? It should be the same as in C++
Avatar of BogoJoker
BogoJoker

Hi shahrine99,

i = 5;
j = 5 - 6;

In the end j is -1, i is 7

Joe P
Oh actually I agree. 0
j = 6-6
i = 7

j should be 0 ur right =)

Joe P
Your right because ++i increments i before the expression is evaluated, and since they are both i they both become 6 then you get 6-6.  The i++ then takes affect after the expression is evaluated.

Joe P
Avatar of HonorGod
Well, since i++ should increment after the reference, and ++i should increment before the usage:

i = 5;    
j = 5 - 5;

j = 0;

whereas i == 5

I agree...
Avatar of shahrine99

ASKER

ok cool thats in Java...what about in c++?
SOLUTION
Avatar of Mayank S
Mayank S
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> what about in c++?

It will vary across platforms. In some cases it will be -2, in some cases it might be 0 because C++ might use stacks for this and the ++i might get evaluated before i++ in certain cases. We are not supposed to answer that ;-) ask in the C++ topic area.
This is homework, isn't it?

And, why didn't you simply try this yourself?

;JOOP!
mayankeagle:
I was taught that ++i inrecrements i Before the statement is evalutated.
I was taught that i++ inrecrements i After the statement is evaluated.
When you said -2 that implies that it happens in real time moving through the statement and I am not too sure that is right.
I of course have not coded this, I'm resisting all urges =)
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
B-grade ?
B-Homework.
>> I was taught that i++ inrecrements i After the statement is evaluated.

Not the entire statement, just the expression or the sub-expression where it is used. Expect it to evaluate after the first usage.
>> Expect it to evaluate

Meaning expect it to 'change the value'