How does C# evaluates AND OR expression with no br

2020-07-18 04:43发布

not sure if this make sense at all im trying to understand how C# process the following logic

false && true || false
false || true && false

basically i'm trying to find out how C# evaluate these expression when there is no parentheses .

标签: c# .net
8条回答
等我变得足够好
2楼-- · 2020-07-18 05:10

The the AND operator has higher precedence than the OR operator (see http://msdn.microsoft.com/en-us/library/6a71f45d.aspx). Meaning && is always evaluated first.

Thus x && y || z is understood to be (x && y) || z.

And a || b && c is understood to be a || (b && c).

查看更多
劳资没心,怎么记你
3楼-- · 2020-07-18 05:11

C# Operators shows operator precedence:

false && true || false    =  (false && true) || false        =  false
false || true && false    =  false || (true && false)        =   false

&& (logical AND) has higher precedence than || (logical OR)

NOTE: it is good practice (some might say best practice) to always use parentheses to group logical expressions, so that the intention is unambiguous...

查看更多
小情绪 Triste *
4楼-- · 2020-07-18 05:14

Everyone said about the operator precedence and the reference tables where you can look that up. But I'd like to give a hint how to remember it. If you think of false as of 0 and of true as of 1 then && is like multiplication and || is like addition (they are actually called logical multiplication and logical addition). The precedence relationship is the same: multiplication is higher then addition. It works the same way:

0 * 0 == 0       |     false && false == false
0 * 1 == 0       |     false && true  == false
1 * 0 == 0       |     true  && false == false
1 * 1 == 1       |     true  && true  == true

0 + 0 == 0       |     false || false == false
0 + 1 == 1       |     false || true  == true
1 + 0 == 1       |     true  || false == true
1 + 1 == 1*      |     true  || true  == true

(*) it's actually 2 capped at 1

And normally, when in doubt, use parenthesis.

查看更多
家丑人穷心不美
5楼-- · 2020-07-18 05:14

The operators will be evaluated in order of operator precedence.

So, basically, AND before ORs. Your examples are the same as:

(false && true) || false
false || (true && false)
查看更多
兄弟一词,经得起流年.
6楼-- · 2020-07-18 05:16

Most importantly... C# uses short circuit operators. So that entire thing is false link text

查看更多
干净又极端
7楼-- · 2020-07-18 05:22

operator precedence short circuit evaluation parenthesis left to right.

查看更多
登录 后发表回答