Java Assignment vs C ++ Operator Operation

This happened when I solved the question "Cracking the Coding interview":

Write a function to replace the number in place (i.e. without temporary variables)

I decided to write my solution in Java (because I plan to use Java in my interviews for internship.)

I came up with a solution in which I was almost sure was the correct answer (because I did it on 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); } 

Of course, this code fulfills the desired result. a == 7 and b == 5 .

Now here is the fun part.

This code will not work in C ++ and this solution will not be at the end of the book.

So my question is: why exactly does my solution work? I assume Java does something different than other languages?

+5
source share
1 answer

See Java Language Specification, Section 15.7 (Evaluation Order) :

The Java programming language ensures that the operands of the operators are apparently evaluated in a specific evaluation order, namely, from left to right.

So, in Java, the order of evaluation is well defined and does what you expect.

The C ++ specification does not provide such a guarantee; this is actually an Undefined Behavior, so the program could literally do something.

Quoted from cppreference , noting that there is no sequence rule for ordering operands to arithmetic operators:

If the side effect of the scalar object is independent of the value of the calculation using the value of the same scalar object, the behavior is undefined.

+5
source

All Articles