Reputation: 638
This occured while I was tackling a 'Cracking the Coding interview' question:
Write a function to swap a number in place (that is, without temporary variables)
I decided to write up my solution in Java (because I plan on using Java in my internship interviews.)
I came up with a solution that I was almost confident was the right answer (because I did it in one line):
public static void main(String args[]) {
int a = 5;
int b = 7;
a = b - a + (b = a);
System.out.println("a: " + a + " b: " + b);
}
Surely enough, this code executes the desired result. a == 7
and b == 5
.
Now here's the funny part.
This code won't run in C++ nor is this solution in the back of the book.
So my question is: Why exactly does my solution work? I am assuming Java does things differently than other languages?
Upvotes: 5
Views: 776
Reputation: 31299
Looks at the Java Language Specification, section 15.7 (Evaluation Order):
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
So in Java the evaluation order is well-defined and does what you expect.
The C++ specification doesn't provide such a guarantee; in fact it's Undefined Behavior so the program could literally do anything.
Quoting from the cppreference, noting that no sequencing rule exists for sequencing operands to arithmetic operators:
If a side effect on a scalar object is unsequenced relative to a value computation using the value of the same scalar object, the behavior is undefined.
Upvotes: 5