Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Operators with ++ and =

Nuwan Hettiarachchi
Greenhorn
Posts: 9
Hi all...
I'm confused with the following syntaxes. First of all I have noticed several posts regarding precedence in this forum and for some Bates has answered saying such topics will be rare in SCJP5.0 onwards. However, since this was a scenario that we have discussed in the class... Can some one give some insight on what is happening in this code. I have put my experimental results on the code saying what were my outputs.

I have tested for two scenarios,
1. with f1() returning 0;
2. with f1() returning i;

Based on the values I get; should I consider for Scenario 1,
i=i++ + (f1(i)) happened like i++ done first and then the incremented value is passed to f1(i) (That should be why I get 1 printed for this), and then again when assigning to i (i=part on Right hand side) the value that is incremented is not considered?

I hope I can figure out answers for other cases if I get my confusion cleared for this...

Nuwan

fred rosenberger
lowercase baba
Bartender
Posts: 12198
35
I'm not sure I understand exactly what you are asking... If i simplify your code to the basics of what i THINK you are asking, we get this:

and you want to know why the result it 1?

i starts as 0. we now get to this line:

i = i++ + (f1(i));

so, first we evaluate i - it's 0, and increment it (that's the i++). we then evaluate i - it's 1, and pass that to f1. f1 returns the value of i, which is 1. we now do the addition. 0 + 1 is 1. we assign that to i.

Let us know if that helps, or if i didn't answer the question.

Nuwan Hettiarachchi
Greenhorn
Posts: 9

I think I have found the answer from you.

first we evaluate i - it's 0, and increment it (that's the i++)

1. Evaluate
3. Use the adjusted value for the method call
4. Still i = i++ + (f1(i)); is evaluated with i's unadjusted value. so i= 0 + 1

My confusion was weather to use the adjusted value or not.

Thank

fred rosenberger
lowercase baba
Bartender
Posts: 12198
35
My confusion was weather to use the adjusted value or not.

it won't matter if you have

or

at least as far as what's passed to f1. in both cases, i will have been incremented to 1 for the method call.

the value used in that addition will be different, though. the first example, the jvm thinks 'use the value of i here, then increment it". in the second case, the jvm thinks "ok, increment i and use that in this spot".

In both cases, by the time you get to the method call, i has become 1.

Ben Souther
Sheriff
Posts: 13411
"Nuwan H",