开发者

What is the meaning of (true && false || true) in C#?

If I have this equation:

    var x = (true && false || true)

Is that equivalent to:

    var x = ((开发者_Go百科true && false) || true)

or:

    var x = (true && (false || true))

And whats the logic behind this?


AND wins over OR.

So it will be

var x = ((true && false) || true)

See Operator precedence and associativity.


In boolean logic, "not" (!) is evaluated before "and" (&&) and "and" is evaluated before "or" (||). By using the double (&&) and the double (||), these operators will short circuit, which does not affect the logical outcome but it causes terms on the right hand side to not be evaluated if needed.

Thus

var x = (true && false || true) evaluates to false|| true which evaluates to true

and

var x = ((true && false) || true) evaluates to false || true which evaluates to true

and

var x = (true && (false || true)) evaluates to true && true which evaluates to true


I believe it's

var x = ((true && false) || true)

...as && has precedence according to MSDN.

You'd think that whoever wrote that particular line of code might have made their intention clear by inserting the parenthesis in the right place. Do everyone else a favour, and add them in.


It's equivalent to

var x = ((true && false) || true)

The && operator has higher precedence than the || operator.

Operator precedence MSDN documentation


&& has higher precedence, so the second form (of the three) is correct. As to the logic, && tends to be vaguely associated with multiplication, and || with addition (if you use zero and non-zero to represent false and true, respectively, the operators have equivalent semantics). But mostly it's just the way it's been since C, and possibly before C.


If you use in this expression || true that mean doesn't matter about other result it always will be true


The above expression evaluates as ((true && false) || true) because of the operator precedence(&& has higher precedence than ||).

Check this link for more information on Operator Precedence: http://msdn.microsoft.com/en-us/library/aa691323(v=vs.71).aspx


&& has a higher precedence than || so the first two use cases will act exactly the same. The braces have no meaning here, just like in:

a * b + c = (a * b) + c

You can control precedence and associativity with braces. so the third use case will check the OR condition and then the AND.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜