今天栽到了算符优先级的手里。
按位与(&)这个操作的优先级居然比不等比较符(!=)的优先级低。
所以下面这样的代码:
#include <iostream>
using namespace std;

int main()
{
unsigned long test = 8;

if (test & (1 << 3) != 0)
{
cout << '1' << endl;
}

if (test & (1 << 3) != (unsigned long)0)
{
cout << '2' << endl;
}

if (test & (1 << 3))
{
cout << '3' << endl;
}

cout << (test & (1 << 3)) << endl;

return 0;
}
其输出结果就是:
没有“1”和“2”。
只要给“test & (1 << 3)”加上括号就正常了:
#include <iostream>
using namespace std;

int main()
{
unsigned long test = 8;

if ((test & (1 << 3)) != 0)
{
cout << '1' << endl;
}

if ((test & (1 << 3)) != (unsigned long)0)
{
cout << '2' << endl;
}

if (test & (1 << 3))
{
cout << '3' << endl;
}

cout << (test & (1 << 3)) << endl;

return 0;
}
所以说,这人还是不能偷懒:要么把优先级全部记住,要么就尽可能多地使用括号来明确运算的优先关系。
反正我是不会去记那个优先级的,感觉挺乱的。分不清的时候要么查一下表,要么加个括号就行了。今天真是一时疏忽,犯下大错。特记录于此,作个教训。
附上Turbo C运算符的优先次序,方便查阅:

按位与(&)这个操作的优先级居然比不等比较符(!=)的优先级低。
所以下面这样的代码:



























3
8
8
只要给“test & (1 << 3)”加上括号就正常了:



























所以说,这人还是不能偷懒:要么把优先级全部记住,要么就尽可能多地使用括号来明确运算的优先关系。
反正我是不会去记那个优先级的,感觉挺乱的。分不清的时候要么查一下表,要么加个括号就行了。今天真是一时疏忽,犯下大错。特记录于此,作个教训。
附上Turbo C运算符的优先次序,方便查阅: