conditional statement with ||

18 visualizaciones (últimos 30 días)
Leor Greenberger
Leor Greenberger el 28 de Sept. de 2011
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?

Respuesta aceptada

Fangjun Jiang
Fangjun Jiang el 28 de Sept. de 2011
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.

Más respuestas (1)

Walter Roberson
Walter Roberson el 28 de Sept. de 2011
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 comentario
Fangjun Jiang
Fangjun Jiang el 29 de Sept. de 2011
+1, that's another sharp catch!

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by