简体   繁体   中英

Are there any guarantees when modifying arguments during method invocation?

In Java when passing arguments to a method and modifying the passed arguments during the method call is it guaranteed that the result is what is expected?
Eg
a.method(++i); etc

Is it guaranteed for instance that inside method the variable i will have the updated value?

Or a.method(i++) Will method get the value of i after incrementing or before?

Also same for all similar cases.
I kind of remember this is forbidden in C++ as implementation specific but perhaps I remember wrong.

The java language specification for prefix/postfix increment/decrement operators:

... the value 1 is added to the value of the variable and the sum is stored back into the variable ... The value of the prefix increment expression is the value of the variable after the new value is stored .

... the value 1 is added to the value of the variable and the sum is stored back into the variable ... The value of the postfix increment expression is the value of the variable before the new value is stored .

I think it's pretty clear. The function will get the incremented value in the prefix case, and not in the postfix case.

The expression ++i is evaluated before the method is called.

From the Java Language Specification's section "Runtime evaluation of method invocation" :

... Second, the argument expressions are evaluated. ... Fifth, a new activation frame is created, synchronization is performed if necessary, and control is transferred to the method code.

And from the Java Language Specification's section "Prefix increment operator" :

The value of the prefix increment expression is the value of the variable after the new value is stored.

在Java中没有问题,方法将收到更新的值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM