...would expect 6 to be printed. Any idea why?
The x++
happens after the value 5
has been read from x
. Remember that what follows the return
statement is an expression. When the return
statement is reached, that expression is evaluated (its value is determined), and then that resulting value is used as the function's return value. So in myfunc
, here's the order of what happens:
- Enter the
try
block.
- Evaluate the expression
x
(e.g., get the value of x
).
- Set that value as the function's return value.
- Enter the
finally
block.
- Increment
x
.
- Exit the function using the return value from Step 3.
So as of when we leave the function, even though x
is 6
, the return value was determined earlier. Incrementing x
doesn't change that.
Your code in myfunc
is analogous to this:
int y = x;
x++;
There, we read the value of x
(just like return x
does), assign it to y
, and then increment x
. y
is unaffected by that increment. The same is true for the return value of the function.
It might be clearer with functions: Assuming a foo
function that outputs "foo"
and returns 5, and a bar
function that outputs "bar"
, then this code:
int test() {
try {
return foo();
}
finally {
bar();
}
}
...executes foo
, outputting "foo"
, then executes bar
, outputting "bar"
, and exits from test
with the return value 5
. You don't expect the function to wait to call foo
until after the finally
occurs (that would be strange), and indeed it doesn't: It calls it when it reaches the return foo();
statement, because it evaluates the expression foo()
. The same is true of return x;
: It evaluates the expression and remembers the result as of that statement.
return
will supersede any other changes. Besides, any changes you make tox
won't be seen outside of the method anyway. You many also want to investigate the differences between post and pre increments – Skirretreturn x++;
in thefinally
block, then it would ;) – Skirrety
it will be 6. ;P – Pervasive