1. 位运算优先级低于逻辑运算符
做leetcode时遇到的,判断一个数某一比特位是否为0。
if ( val & 2 == 0) {
// do someting...
}
万万没想到&
运算符的优先级是低于==
的,debug了好久,得加上括号。
1.1 验证
#include <iostream>
int main( int argc, char *argv[]){
int val = 2;
if ( val & 1 == 0) {
std::cout << "without (): bit 1 is 0" << std::endl;
}
else {
std::cout << "without (): bit 1 is 1" << std::endl;
}
if ( (val & 1) == 0) {
std::cout << "with (): bit 1 is 0" << std::endl;
}
else {
std::cout << "with (): bit 1 is 0" << std::endl;
}
return 0;
}
输出结果为
without (): bit 1 is 1
with (): bit 1 is 0
2. 移位运算符优先级低于算术运算符
这是在写二分的时候遇到的, l + (r-l) >> 1
的值永远为r >> 1
应该写作l + (r - l >> 2)
。文章来源:https://www.toymoban.com/news/detail-585014.html
2.1 验证
#include <iostream>
int main( int argc, char *argv[]){
int l = 2, r = 8;
int mid = l + (r - l) >> 1;
int mid2 = l + ( r - l >> 1);
std::cout << "mid: " << mid << std::endl;
std::cout << "mid2: " << mid2 << std::endl;
return 0;
}
输出结果为文章来源地址https://www.toymoban.com/news/detail-585014.html
mid: 4
mid2: 5
到了这里,关于C/CPP位运算优先级的坑的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!