C/CPP位运算优先级的坑

1. 踩坑

做leetcode时遇到的,判断一个数某一比特位是否为0。

if ( val & 2 == 0) {
	// do someting...
}

万万没想到&运算符的优先级是低于==的,debug了好久,得加上括号。

2. 验证

#include 
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

你可能感兴趣的:(c语言,c语言,开发语言)