C++警告:建议在 | 操作数中的算术周围使用括号
代码
A = B|C|D|E;
我有一个类似抛出警告“建议在|操作数中的算术周围使用括号”的
预计表达式需要运算符的高优先级括号,尝试了以下方法:
A=(B|C)|(D|E);
又一个 as :
A=(((B|C)|D)|E);
仍然存在相同的警告。
请帮我解决这个问题。
谢谢, Sujatha
B、C、D 是枚举,E 是整数。
I have a code like
A = B|C|D|E;
Throwing the warning "suggest parentheses around arithmetic in operand of |"
Expecting that expression needs high priority paranthesis for operators, tried the following ways:
A=(B|C)|(D|E);
one more as :
A=(((B|C)|D)|E);
Still the same warning persists.
Please help me in resolving this.
Thanks,
Sujatha
B, C,D are enums and E is an integer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的表达式中有一些算术运算符,它并不是真正简单的 B,或者不是真正简单的 C,等等。编译器建议你将任何一个表达式加上括号,以便读者看到你写的是什么意思。如果你不加括号,每个人都必须准确记住优先级是什么,并且他们必须弄清楚你是否记得你何时写的。
试试这个:(B)|(C)|(D)|(E)。
You have some arithmetic operator in your expression that isn't really simply B, or that isn't really simply C, etc. The compiler is suggesting that you parenthesize whichever expression so that readers will see that you wrote what you meant. If you don't parenthesize, everyone has to remember exactly what the priorities are, and they have to figure out if you remembered when you wrote it.
Try this: (B)|(C)|(D)|(E).
这是一个奇怪的警告。当您使用不同的运算符并且这些运算符具有不同的优先级时,您才真正需要注意优先级。例如,在算术中,乘法的优先级高于加法。
但在这种情况下,您多次只使用一个运算符。按位或是结合律和交换律(
(A | B) | C == A | (B | C)
和A | B == B | A
),所以确实有没有理由发出警告。This is a weird warning. You only really need to pay attention to precedence when you're using different operators and those operators have different precedences. For instance, in arithmetic multiplication has higher precedence than addition.
But in this case you're using only one operator multiple times. Bitwise or is associative and commutative (
(A | B) | C == A | (B | C)
andA | B == B | A
) so there's really no reason for the warning.