单条语句:i++;
、++i;
和 i += 1;
等价。
int i = 0;
++i; // 或者i++;或者i += 1;
cout << i <<endl; // 输出i都为1
作为返回值时,i++
返回自增前的值,++i
和i += 1
都返回自增后的值
int i = 0;
int b = i++; // i不受影响,自增成1。但作为返回值传递给b还是自增前的0
cout << i << b << endl; // 输出i是1,b为0
int i = 0;
// 或者int b = (i += 1);
int b = ++i; // i不受影响,变成1。作为返回值传递给b是自增后的1
cout << i << b << endl; // 输出i是1,b为1
int i = 0;
// 或者if(i += 1)
if (++i)
{
cout <<"yes" << endl; // 输出yes,++i返回自增后的1
}
int i = 0;
if (i++)
{
cout <<"yes" << endl; // 没有输出,i++返回自增前的0
}
综上,++i
和i += 1
无论在哪儿都是等价的。单条自增语句,三条语句等价。作为返回值使用时i++
和++i
(i += 1
)是有区别的。
by @sunhaiyu
2016.8.24