Reputation: 13
I am making a frequency analysis thingy, and I want it to automatically switch letters. I know what to switch to, but can you have your code like:
if(a > b && a > c && a > c) { //code }
I have been told that it won't evaluate the rest of the code, if a > b. Is that true?
Upvotes: 0
Views: 99
Reputation: 610
actually this is called the short-circuit evaluation where different statements have AND operator between them the C# run-time will evaluate the whole expression to false if one statement is false then ignores the rest of the statements evaluation.
if you want the to evaluate all the expressions regardless of the result of each one alone then use single & rather then two &&. it will compare them bit wise and it will enforce to evaluate all the statements to determine the final result.
if(a > b && a > c && a > c)
instead
if(a > b & a > c & a > c)//it will evaluate all the conditions before the final result
For more check this: LINK
Upvotes: 0
Reputation: 186688
When .Net computes &&
it uses short-circuiting: it checks the first expression (a > b)
and
if it false does nothing, in case of true checks the second (a > c)
etc., so your case
if(a > b && a > c && a > d) { //code }
is equal to
if (a > b)
if (a > c)
if (a > d) { //code }
Upvotes: 1
Reputation: 16922
if(a > b && a > c && a > c)
if a > b
is false then it won't validate a > c
. As both has to be true in order for the code to be executed. However if a > b
is true, then it will check a > c
as well.
Also, it makes no sense to have a > c
two times.
If just one of the comparisons has to be true, you can use the ||
operator.
Upvotes: 0