为什么按位运算符需要括号? [英] why bitwise operators require parentheses?

查看:129
本文介绍了为什么按位运算符需要括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
using namespace std;
int main()
    {

    int n;
    cin>>n;
    if(n&1==0)   //without using bracket  (n&1)
        cout<<"Number is even";
    else
        cout<<"Number is odd";
    return 0;
    }

输出:奇数//对于n = 6

output : odd //for n=6

#include<iostream>
    using namespace std;
    int main()
        {
        int n;
        cin>>n;
        if((n&1)==0)
            cout<<"Number is even";
        else
            cout<<"Number is odd";
        return 0;
        }

输出:甚至//对于n = 6

output : even //for n=6

每当使用按位运算符时,是否都必须使用括号?

Do we have to use parentheses whenever we use bitwise operators?

推荐答案

根据运算符优先该表达式:

n&1==0

等效于:

n&(1==0)

表示运算结果 1 == 0 始终为 false ,与二进制AND和 n 一起使用.布尔值 false 隐式转换为 int ,这是必需的通过二进制运算,其值为0.由于二进制AND与0始终为0,所以代码被卷积表示:

which means result of operation 1==0 which is always false is used with binary AND with n. Boolean false is implicitly converted to int which is required by binary operation and value is 0. As binary AND with 0 is always 0 that code is convoluted way to say:

if(0) 
    cout<<"Number is even";
else
    cout<<"Number is odd";

和0会以 false 的形式转换回布尔值,因此您始终会得到"Number is奇数"输出.是的,在这种情况下,需要使用方括号.

and 0 converted back to boolean as false so you always get "Number is odd" output. So yes, brackets are required in this case.

我的问题是,每当我们使用按位运算符时,都必须放括号吗?

my question is do we have to put bracket whenever we are using bitwise operators?

否,当涉及其他优先级更高的操作时,必须使用它们.不一定必须总是这样,但是如果您愿意,可以随时将它们放上.

No, you have to use them when other operations with higher precedence are involved. It does not have to be always, but if you prefer you can always put them.

这篇关于为什么按位运算符需要括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆