C语言 为什么 Clang 会警告:“||”内的“&&”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16939888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:35:28  来源:igfitidea点击:

Why does Clang warn: `'&&' within '||'`?

cclang

提问by mxcl

My understanding is the parentheses make no difference, so is there any reason (other than to “improve“ code-clarity) that Clang warns this as a default? I prefer not to add the parentheses as I dislike adding code for code's sake.

我的理解是括号没有区别,那么 Clang 是否有任何理由(除了“提高”代码清晰度)将此作为默认警告?我不喜欢添加括号,因为我不喜欢为了代码而添加代码。

src/websocket.c:420:43: warning: '&&' within '||' [-Wlogical-op-parentheses]
        if (rv == 0 && N != 0 || rv == -1 && errno == ECONNRESET) {
                              ~~ ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~
src/websocket.c:420:43: note: place parentheses around the '&&' expression to
      silence this warning
        if (rv == 0 && N != 0 || rv == -1 && errno == ECONNRESET) {
                                 ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~

采纳答案by Wooble

The natural tendency is to read it left to right, and it's easy to forget the operator precedence. That said, it's just a warning, and if you know what you're doing and your own style allows it, feel free to suppress it.

自然的趋势是从左到右阅读它,很容易忘记运算符的优先级。也就是说,这只是一个警告,如果您知道自己在做什么并且您自己的风格允许,请随意压制它。

回答by unwind

I'm guessing because it's simply a bit unclear, unless the reader is very good at C's operator precedence rules.

我猜测是因为它只是有点不清楚,除非读者非常擅长C 的运算符优先级规则

Your expression is like this:

你的表情是这样的:

if (A && B || C && D)

and since &&has higher precendence than ||, it means

并且由于&&优先级高于||,这意味着

if ((A && B) || (C && D))

which I guess is what you mean, but it's not very clear when reading.

我想这就是你的意思,但阅读时不是很清楚。