What does it mean to say that an expression is short-circuited?

Asked

Viewed 468 times

1

In the documentation PHP, about operators says:

// foo() will never be called because all the expression short circuit.

What does it mean to say that all expression is short-circuited? What happens to the script at runtime?

<?php

// --------------------
// foo() nunca será chamada porque toda a expressão sofre curto circuito

$a = (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());

1 answer

1


Short circuit evaluation is something implemented by compilers/interpreters to save resources and speed up condition assessment. In a compound conditional test, whether the first condition can ensure the execution or not of the block.

For example:

  • with the variable $a, as the first condition is already false and the operator is a && (And): Fake and anything will always give phony;
  • with the variable $b, the first condition is true and the operator is a || (OR): REAL OR ANYTHING will always give true;
  • the examples $c and $d follow the same idea, respectively.

The link quoted by @rray about operators precedence is very valid!

I add the explanation about each operator’s truth table here.

And also the specific link on short circuit, found here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.