Search code examples
if-statementpseudocodeshort-circuiting

Short Circuiting: How would I write if then else with short-circuiting?


Is it possible to write a one-line if then else statement in a language that supports short-circuiting? It doesn't have to be language specific, just pseudocode.

In case you didn't know, short-circuiting means that a language will evaluate exp1 || exp2 || exp3 || exp4... (|| is the or operator) by first executing exp 1, then if it returns true, execute exp 2, and so on... However, the moment exp n returns false, it does not continue evaluating exp n+1 and anything after that.


Solution

  • Let's say you want to express:

    if p then f() else g()
    

    Using only || and &&, both short circuiting. You can do that like this:

    (p && ( f() || 1 )) || g()
    

    To test it, a quick script:

    $ perl -E '$p=1; ($p && ( f() || 1 )) || g(); sub f { say "f() called" } sub g { say "g() called" }'
    f() called
    $ perl -E '$p=0; ($p && ( f() || 1 )) || g(); sub f { say "f() called" } sub g { say "g() called" }'
    g() called
    $