There’s something called short-Circuit. Relational operators operate this way. They evaluate until they are sure of the result. When the other operands can no longer alter the result no matter their values he no longer tries to evaluate anything and makes the decision.
This is useful because it gives better performance and avoids possible side effects that should eventually be avoided even depending on the previous condition. So:
if ( $a() && $b() && $c() ) fazAlgo;
Is the same as:
if ( $a() )
if ( $b() )
if ( $c() )
fazAlgo;
That is, if you don’t get into the first one if
will not get into the others. So it becomes easier to see. And interestingly enough programmer writes the second example without realizing that he could write in a single line.
Like the AND requires that all operating be true to result in true when a false tense is impossible for others to reverse the situation, has no reason to evaluate others.
The same can happen with OR. Only in this case the situation is different. This operator requires only one operand to be true for the final result to be true. If the first comes true, he will no longer look at the others:
if( $a() || $b() || $c() ) fazAlgo;
Is the same as:
if ( $a() ) fazAlgo;
else if ( $b() ) fazAlgo; //faz algo igual
else if ( $c() ) fazAlgo; //tem que ser igual
I put in the Github for future reference.
Just the $a()
give away true
and $b()
and $c()
nor will they be executed. If he gives false
of course it will evaluate $b()
, then the decision will be evaluated $c()
depends on the outcome of it.
This can be observed with other relational operators (at least in some languages).
There’s language that doesn’t embrace it.
The bit operators (eg.: &
, |
) do not have the feature of closing the circuit and all perform always. Even they are used when the feature is not desired.
There is a question with a classic example of its use. You have a first operand that checks if a condition is met. The second operand will cause it to work correctly only if the first one is true. Typical of checking an object is null before accessing it.
I’ve also noticed this in C# for example when I want to compare the property of an object, and this object is
null
, C# launches aexception
, for this I compare before, in the sameif(objeto != null && objeto.propriedade == valor)
, does not occur toexception
, @bigown’s response helped me clear this up as well– Marco Giovanni
@Marcogiovanni this is purposeful even to solve this kind of question. Without the Circuit short the code would have to be complicated.
– Maniero