0

if (!d1.x0((long) d1.x1, out d2) || d1.x2 != 0 && d1.x2 != e1.x3 || d1.x4 != x4.None && d1.x4 != e1.x5 || d1.x6 != 0UL && (long) d1.x6 != e1.x6)

I spotted this in production C# code (var names replaced for anonymity) and I cannot understand if that statement can work in C#? or maybe other languages too?

I thought || needs to be explicitly grouped with a () if mixed with &&

thevikas
  • 1,618
  • 1
  • 14
  • 31
  • [It is in the documentation](https://learn.microsoft.com/en-us/cpp/c-language/precedence-and-order-of-evaluation?view=msvc-160) – Ondrej Tucny Sep 19 '21 at 12:39

1 Answers1

2

If it compiles in C# it works. That doesn't mean it's correct. With your variable-name changes it is https://WorseThanFailure.com - worthy hard to read and reason about.

As you know, the language evaluates && and || operators, absent any parentheses, from left to right, with the same operator precedence. But conditionally! In a && b, if a is false b is not evaluated. A similar rule applies to ||.

So this very well could be correct. If it's in production code, and you're not chasing a bug in this part of the code you'd be wise not to touch it. If you do rewrite it, you must understand the desired application logic completely. And, you must inspect your rewrite very carefully and test the resulting code: this kind of logic is notoriously easy to screw up when you rewrite it.

C# got this && / || stuff from the C language. So did C++, Java, Javascript, and many other languages. It's incredibly useful. Time you spend becoming adept with it is time well spent.

O. Jones
  • 103,626
  • 17
  • 118
  • 172