shejizhe08
2019-08-31 14:08
采纳率: 100%
浏览 273

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条回答 默认 最新

相关推荐 更多相似问题