Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java assignment operator behavior vs C++

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?

like image 587
Jurko Guba Avatar asked Sep 17 '15 05:09

Jurko Guba


People also ask

What are the advantages of assignment operator in Java?

The basic advantage of compound assignment operators is that it saves a lot of code within the Java language program.

What are the different types of assignment operator?

There are two kinds of assignment operations: simple assignment, in which the value of the second operand is stored in the object specified by the first operand. compound assignment, in which an arithmetic, shift, or bitwise operation is performed before storing the result.

Is == an assignment operator?

The “=” is an assignment operator is used to assign the value on the right to the variable on the left. The '==' operator checks whether the two given operands are equal or not.


1 Answers

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.

like image 128
Erwin Bolwidt Avatar answered Sep 24 '22 21:09

Erwin Bolwidt