i++和++i的區別
阿新 • • 發佈:2020-12-25
技術標籤:C語言
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;
所以兩個
兩個值出來後撕逼不一樣的。