今天栽到了算符优先级的手里。
按位与(&)这个操作的优先级居然比不等比较符(!=)的优先级低。
所以下面这样的代码:
#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运算符的优先次序,方便查阅:

按位与(&)这个操作的优先级居然比不等比较符(!=)的优先级低。
所以下面这样的代码:
#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;
}
3
8
8
只要给“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运算符的优先次序,方便查阅:
本文通过一个具体的C++示例揭示了按位与运算符(&)与不等比较符(!=)之间的优先级差异。当这两种操作符混合使用时,若不恰当使用括号可能导致逻辑错误。文章强调了理解运算符优先级的重要性,并推荐了在不确定时使用括号确保代码正确执行的方法。

704

被折叠的 条评论
为什么被折叠?



