C++ and PHP vs C# and Java - unequal results

后端 未结 4 1841
天涯浪人
天涯浪人 2021-01-01 09:41

I found something a little strange in C# and Java. Let\'s look at this C++ code:

#include 
using namespace std;

class Simple
{
public:
    s         


        
4条回答
  •  孤城傲影
    2021-01-01 10:36

    According to the Java language specification:

    JLS 15.26.2, Compound Assignment Operators

    A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)) , where T is the type of E1 , except that E1 is evaluated only once.

    This small program demonstrates the difference, and exhibits expected behavior based on this standard.

    public class Start
    {
        int X = 0;
        int f()
        {
            X = X + 10;
            return 1;
        }
        public static void main (String[] args) throws java.lang.Exception
        {
            Start actualStart = new Start();
            Start expectedStart = new Start();
            int actual = actualStart.X += actualStart.f();
            int expected = (int)(expectedStart.X + expectedStart.f());
            int diff = (int)(expectedStart.f() + expectedStart.X);
            System.out.println(actual == expected);
            System.out.println(actual == diff);
        }
    }
    

    In order,

    1. actual is assigned to value of actualStart.X += actualStart.f().
    2. expected is assigned to the value of the
    3. result of retrieving actualStart.X, which is 0, and
    4. applying the addition operator to actualStart.X with
    5. the return value of invoking actualStart.f(), which is 1
    6. and assigning the result of 0 + 1 to expected.

    I also declared diff to show how changing the order of invocation changes the result.

    1. diff is assigned to value of the
    2. the return value of invoking diffStart.f(), with is 1, and
    3. applying the addition operator to that value with
    4. the value of diffStart.X (which is 10, a side effect of diffStart.f()
    5. and assigning the result of 1 + 10 to diff.

    In Java, this is not undefined behavior.

    Edit:

    To address your point regarding local copies of variables. That is correct, but it has nothing to do with static. Java saves the result of evaluating each side (left side first), then evaluates result of performing the operator on the saved values.

提交回复
热议问题