C语言中的++运算府,曾让多少英雄为之折腰.最是灵活的地方,也是最容易出错的地方.我们看一下下面一个例题,在后面我加了注解,可以帮大家绕过陷阱.
#include <iostream>
using namespace std;
int main()
{
int a = 0,b = 1;
int c = 0,d = 1;
if (a++ && b++) // a = 1;b=1;(a++)=0;(b++)=1;
a++,b++;// because (a++) = 0,so this line will not execute;
if (a++ || b++) // a = 2; in or operate,first eval is true,next will not execute,b will keep its value;
a++,b++;// a = 3; b = 2;
c = d +++ 1; // => c = (d++) + 1; => c = 1 + 1 = 2;
cout << "a:" << a << endl;
cout << "b:" << b << endl;
cout << "c:" << c << endl;
cout << "d:" << d << endl;
}
|
需要注意的地方是:
1).对于++运算符涉及到的表达式和值的区别;
2).在进行&&及||操作时的操作问题.尤其是||操作时,如果前面的条件为真时,后面的操作是不进行的.
阅读(1389) | 评论(0) | 转发(0) |