conditional statement with ||

조회 수: 29 (최근 30일)
Leor Greenberger
Leor Greenberger 2011년 9월 28일
Say I have
If A && B && C
...do something if A = B = C = true
end
Is it faster, however to do:
If ~(A || B || C)
..do something if A or B or C = false
end
I am wondering if the latter statement is faster because it should be able break if any of the conditions are false and not test the rest. But I am wondering if the negation forces all of the conditions to be tested first?

채택된 답변

Fangjun Jiang
Fangjun Jiang 2011년 9월 28일
If A is false, then A && B will be short-circuited. No need to use the latter approach. Use the first one because it's easy to read.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2011년 9월 28일
The two expressions are not equivalent.
A && B && C
is true only if A and B and C are all true.
~(A||B||C)
is true only if A and B and C are all false, not if one of them is false.
The logical or equivalent of A && B && C is
~(~A || ~B || ~C)
  댓글 수: 1
Fangjun Jiang
Fangjun Jiang 2011년 9월 29일
+1, that's another sharp catch!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by