c++中++i与i++的区别是什么
c++中的++i和i++
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
// c++中++i与i++的区别
#include "stdafx.h"
#include<iostream>
using namespace std;
int main(){
int i1 = 7;
int a = i1++; //先赋值,再自加
cout << "a = " << a << " i1 = " << i1<<endl;
int i2 = 7;
int b = ++i2; //先自加,再赋值
cout << "b = " << b << " i2 = " << i2<<endl;
return 0;
}
运行结果
a = 7 i1 = 8
a = 8 i2 = 8
int i = 0;
int c = (++i)+(i++)+(++i)+(i++);
cout << "c = "<<c<< " i = "<<"i" <<endl;
运行结果
c = 8 i = 4
分析
两次++i使得i的值变为2,故此 c = 2+2+2+2=8,i++在此处即为i=2
在赋值c后,两次i++使得i的结果再加2,故最终为4