"Redundant" parentheses incorrect? (Visual Studio Resharper c#)

Answered

Resharper is telling me the parentheses around "A" "B" in "(A && B)" are redundant.

To me, they are not. A and B must be evaluated first before we know the result of this operation. Then the software can move onto the other or statements if (A && B) == false... Tell me if I'm missing something here? Is there something I'm not understanding?

bool A, B, C, D; //yes, I know I'm not assigning these values, for brevity's sake, in this post.
if ((A && B) || C || D)
{

}
0
3 comments

Technically, R# is correct. The && and || operators have the same precedence, so the operations are evaluated from left to right.

Both ((A && B) || C || D) and (A && B || C || D) compile to the same IL.

0

Hello gruthor, thank you for your question. Please try setting "&& || ??" value for ReSharper | Options | Code Editing | C# | Syntax Style | Parentheses | Add parentheses to avoid non-obvious precedence | When the operations from the following groups are nested option. Does it help?

Richard Deeming, thank you so much for your help!

0

Richard Deeming, Maria Pleskunina  Thanks! This actually has cleared up a critical understanding for me about how order of operations works! Did some tests of my own to prove to myself this is the right interpretation. I guess this is a case where a redundant parentheses may not be such a bad thing, at least from a code legibility standpoint, even though the compiler doesn't see a difference--for our human brains it may just be better to put them in.

Richard Deeming actually I did some tests: && and II do NOT have the same precedence. && is evaluated before II, same as & is evaluated before I. Also, see: https://docs.microsoft.com/en-us/cpp/c-language/precedence-and-order-of-evaluation?view=msvc-170 

So, R# is correct in saying that the parentheses in first example are not necessary, but in the following example, the parentheses are not redundant (and R# correctly does not flag this usage). So, nothing wrong with R# but wanted to put this clarification here because it seems important.

 

bool a, b, c;
if ((a || b) && c)
{
}

 

 

0

Please sign in to leave a comment.