Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

c# - Difference between eager operation and short-circuit operation? (| versus || and & versus &&)

I am (still) learning C# - and I thought I understood the difference between & & && as well as | & ||...

However, after just reading another guide, it is clear I don't get it.

I wrote a little truth table and as I thought, they return the same. From what I have read, using double symbols sounds like a superior solution, but I am a little confused on the difference and was wondering if anyone could please explain/give an example why/when you would use one instead of the other - I tried reading the MSDN example, but it left me more confused than when I started!

enter image description here

(And, if anyone can come up with a better title, feel free to change it... very awkward to write one!)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

& can be used in two different ways: bitwise "and" and logical "and"

The difference between logical & and && is only that in case you use &, the second expression is also evaluated, even if the first expression was already false. This may (for example) be interesting if you want to initialize two variables in the loop:

if ((first = (i == 7)) & (second = (j == 10))) { //do something }

if you use this syntax, first and second will always have a value, if you use

if ((first = (i == 7)) && (second = (j == 10))) { //do something }

it may be that only first has a value after the evaluation.

It is the same for | and ||: In case you use |, both of the expressions are always evaluated, if you use || it may be that only the first expression is evaluated, which would be the case if the first expression is true.

In contrast, in other applications && can be the better choice. If myNumber is of type int?, you could have something like

if (myNumber != null && myNumber.Value == 7)

and this would only evaluate myNumber != null at first, and it would only evaluate the second expression, if the null check was okay.

if (myNumber != null & myNumber.Value == 7)

would finish with a NullPointerException during the evaluation of the second expression, if myNumber was null. Therefore, you would use && in this context.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...