c++中自增运算是否会影响赋值运算?

n = 1;
c = (n = 2)* ++n;
都是用VS2015运行结果是9,但是9=3*3,难道后面的自增会影响前面的赋值?
n=2的赋值结果应该是2,为何会变成3呢?

下边是代码测试,VS2015


#include "stdafx.h"
#include <iostream>
#include "stdlib.h"
#include "Test.h"
using std::cout;
using std::cin;
using std::endl;


int add(int a, int b)
{
    cout << "a = " << a << ", b = " << b << endl;
    int c = a + b;
    return c;
}

int main()
{

    int n = 1;
    int c = add( n = 2, ++n);
    cout << "c = " << c << ", n = "<< n<<endl;
    cout << "---------------" << endl;
    n = 1;
    c = add(++n, n = 2);
    cout << "c = " << c << ", n = " << n << endl;
    cout << "---------------" << endl;
    n = 1;
    c = add(n = 2, n++);
    cout << "c = " << c << ", n = " << n << endl;
    cout << "---------------" << endl;
    n = 1;
    c = add(n++, n = 2);
    cout << "c = " << c << ", n = " << n << endl;
    cout << "---------------" << endl;
    n = 1;
    c = (n = 2)* ++n;
    cout << "c = "<< c << ", n = "<< n << endl;
    cout << "---------------" << endl;
    system("pause");
    return 0;
}

运行结果:

图片说明

2个回答

    int k = 1;
00007FF6C5061575  mov         dword ptr [k],1  
    int t=(k = 2)*++k;
00007FF6C506157D  mov         dword ptr [k],2  
00007FF6C5061585  mov         eax,dword ptr [k]  
00007FF6C5061589  inc         eax  
00007FF6C506158B  mov         dword ptr [k],eax  
00007FF6C506158F  mov         eax,dword ptr [k]  
00007FF6C5061593  imul        eax,dword ptr [k]  
00007FF6C5061598  mov         dword ptr [t],eax 

从汇编来看,vs编译器是先执行了k=2,然后++k,最后计算k*k

因为k=2返回的是左值而不是右值,所以这样是合理的

比较早的编译器在定义k的时候加上volatile会出现返回右值的情况,这种情况下结果会是6

因为自增的优先级高于乘号的优先级,当执行完括号里面的程序之后执行的是自加的语句,此时n再次被赋值此时n=3,本来寄存器中n=2此时被改变n=3,之后才执行乘法

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问