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

2019-02-07 17:31发布

问题:

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.

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) {
                                 ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~

回答1:

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.



回答2:

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

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.



标签: c clang