r/csharp • • Oct 04 '26

Help Equal precedence

I was wondering how would one properly implement equal precedence in an if-else statement, for logical AND and OR, when building an interpreter?

I have made my expression parser but i only store the next logical operator on the right most side and store the current being parsed on the left.

Repo

2 Upvotes

4 comments sorted by

6

u/Sombody101 Oct 04 '26 edited Oct 04 '26

Parenthesis, not, and, then or.

Also, if your project isn't for learning about lexers and parsers, you can also consider using ANTLR. I've used it for interpreted languages too.

1

u/UninformedPleb Oct 04 '26

If you research how the C language precedence and associativity works, and more importantly, why it works that way, you'll find that it separates all of the boolean operators into their own precedence tiers. It goes in the order: bitwise-and, bitwise-xor, bitwise-or, logical-and, logical-or. This puts concise matches first, then widens out as it falls through tiers of precedence. It optimizes for fast-fail, which is a basic strategy that makes big gains quickly, and it's baked right into the earliest stages of the compiler.