i++与++i
1. 样例
#include <iostream>
using namespace std;
void printVal(int before, int after, int* intp) {
cout << "before: " << before << endl;
cout << "after: " << after << endl;
cout << "in function: " << *intp << endl;
}
2. 测试
int main() {
cout << "i++" << endl;
int a = 0;
printVal(a++, a, &a);
cout << "++i" << endl;
int b = 0;
printVal(++b, b, &b);
}
运行结果如下
i++
before: 0
after: 1
in function: 1
++i
before: 1
after: 1
in function: 1
结论
- i++在调用处即进行了自增,而不是等到当前语句结束后才进行自增。
- i++返回值为i,而++i返回值为i + 1。