5

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?

9
  • 1
    I think (b = a) doesn't return anything in C++. Or maybe I'm wrong, I don't know C++. Commented Sep 17, 2015 at 5:30
  • 1
    For java: stackoverflow.com/questions/12850676/… Commented Sep 17, 2015 at 5:30
  • 1
    @Sweeper b = a is evaluated to an lvalue of b, with the side effect of assignment. Commented Sep 17, 2015 at 5:32
  • 2
    @Sweeper As an expression, it yields the value assigned .. however, C/C++ have the 'fun' issue of sequence points and thus Undefined Behavior. In Java it's defined behavior, albeit 'too clever for me'. Commented Sep 17, 2015 at 5:33
  • 1
    Search for and read about sequence points (I also recommend this evaluation-order reference). Commented Sep 17, 2015 at 5:34

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

In contrast, "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." (cppreference), noting that no sequencing rule exists for sequencing operands to arithmetic operators.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.