2. for循环中的自增量及后增量
for语句中判断语句包含自增量及后增量
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; (++i) < 1; )
{
cout << "测试第一个循环 " << endl;
}
for (int i = 0; (i++) < 1; )
{
cout << "测试第二个循环" << endl;
}
}
以上程序的输出为:
测试第二个循环1
请按任意键继续. . .
证明,后增量 i++ 在for的第一次循环中是不会 +1 的。
for语句中的自增与循环体里的自增的执行顺序:对于判断语句中的i++,在for中的三条语句都执行完后,执行i++,再进入循环体。
//思考以下程序的输出
#include <iostream>
using namespace std;
int main()
{
int a,x;
for(a=0,x=0;a<=1 && !x++;)
{
a++;
}
}
输出12
解析:
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int n = 'c';
switch (n++)
{
case 'c': printf("c");
case 'd': printf("d");
}
return 0;
}
//输出 cd
1. 指针与++
int array[] = {6,7,8,9,10};
int* ptr = array;
*(ptr++) += 123;
//思考输出
printf("%d,%d\n",*ptr, *(++ptr));
//结果输出8 8
-
要点1
*(ptr++) +=123 等价于 *ptr += 123; ptr++;
-
要点2
printf计算参数是从右到左压栈(运算)的。也就是说在
printf("%d,%d\n",*ptr, *(++ptr))
语句中,会先执行++ptr,再执行最右边的语句*ptr,再向左执行(依然是)*ptr