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条回答
Rolldiameter
2楼-- · 2020-07-18 05:23

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 =)

查看更多
地球回转人心会变
3楼-- · 2020-07-18 05:24

&& 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
查看更多
登录 后发表回答