java - 运算顺序问题
大家讲道理
大家讲道理 2017-04-18 09:27:33
0
2
310

java代码

import javax.swing.*;

public class test12
{
    public static void main(String[] args)
    {
        int a = 3;
        a -= a += a * a;
        System.out.println(a)
    }
}

c++代码

#include <iostream>

using namespace std;

int main()
{
    int a = 3;
    a -= a += a * a;
    cout << a << endl;
    return 0;
}

为什么两个程序打印出的a的值不同,java是-9,c++是0
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
黄舟

This problem has nothing to do with operators, they are all calculated from right to left, but the difference is caused by the compiler's inconsistent processing of value types.
For gc-like languages, including (java,c#,php,javascript), etc., the intermediate operation results of single-sentence instructions will be cached. Since C/C++ is directly compiled into assembly instructions and does not have the support of a virtual machine or engine, this step will not be possible.
In layman’s terms, for c++:

a=3*3;//9
a=a+a;//18
a=a-a;//0

That is to say, the value of a is a value type and will be updated at any time as a changes. No matter what value a is initially set to, the result is 0. (a-a).
However, for other languages, the virtual machine or engine will automatically save the calculation results of each step.

int a=3;
int result=0;
result=a*a;//9
result=a+result;//3+9=12
result=a-result;//3-12=-9

Above.
Extension: Research on a weird addition algorithm in PHP

洪涛

Don’t worry about this, just add () where you feel vague.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template