Java Reference
In-Depth Information
idiom is undefined even in C and C++.
For what it's worth, it is possible to write a Java expression that swaps the contents of two variables
without using a temporary. It is both ugly and useless:
// Rube Goldberg would approve, but don't ever do this!
y = (x ^= (y ^= x)) ^ y;
The lesson is simple: Do not assign to the same variable more than once in a single expression.
Expressions containing multiple assignments to the same variable are confusing and seldom do
what you want. Even expressions that assign to multiple variables are suspect. More generally,
avoid clever programming tricks. They are bug-prone, difficult to maintain, and often run more
slowly than the straightforward code they replace [EJ Item 37].
Language designers might consider prohibiting multiple assignments to the same variable in one
expression, but it would not be feasible to enforce this prohibition in the general case, because of
aliasing. For example, consider the expression x = a[i]++ - a[j]++ . Does it increment the same
variable twice? That depends on the values of i and j at the time the expression is evaluated, and
there is no way for the compiler to determine this in general.
< Day Day Up >
 
 
Search WWH ::




Custom Search