i++
是优先对i进行判断和操作,操作完之后在对i进行+1操作。
++i
优先对i加1,然后在继续后续操作
示例 1
#include <iostream>
#include <cstdlib>
using namespace std;
int main(void) {
int a = 0;
int b = 0;
cout << "a++ = " << a++ << endl;
cout << "++b = " << ++b << endl;
system("pause");
return 0;
}
结果为:
示例2
#include <iostream>
#include <cstdlib>
using namespace std;
int main(void) {
int a = 1;
int x = 1;
cout << "a = " << a << endl;
cout << "x = " << x << endl;
int b = a++;
int c = ++x;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
system("pause");
return 0;
}
结果为:
在这个时候i++就是以下步骤:
先将a的值赋给b,然后对a进行+1;
int b = a;
a = a + 1;
相对的++i就是先对i进行加1,然后在将i的值赋给后续:
x = x + 1;
c = x;
所以两个
两个值出来后撕逼不一样的。