How does C# evaluates AND OR expression with no brackets
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 .
&&
has a higher precedence than ||
so it's evaluated first. Effectively, they're equivalent to:
false && true || false => (false && true) || false => false
false || true && false => false || (true && false) => false
If you're unsure, use the parentheses. They have no real negative impact and anything that makes code more readable is generally a good thing.
Perhaps a better example (so that the results are different) would have been:
true && false || false => (true && false) || false => false
true || false && false => true || (false && false) => true
The compiler figures it out because the standard specifies operator precedence.
That said, if an expression requires you to think for more than a second about what is happening in what sequence... use parentheses to make it clear =)
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...
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.
The operators will be evaluated in order of operator precedence.
So, basically, AND
before OR
s. Your examples are the same as:
(false && true) || false
false || (true && false)
Most importantly... C# uses short circuit operators. So that entire thing is false link text
operator precedence short circuit evaluation parenthesis left to right.
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)
.
精彩评论