Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common term for the "value-based" OR operator

Just a quick question

 printf("%d", 99 || 44) prints "1" in C
 print 99 || 44 prints "99" in perl

There are two different kinds of evaluation. Does each one have a name?

edit: i'm interested to know how this Perl evaluation is commonly called when compared to C. When you say "C example is X, and perl example is not X, but Y" which words would you use for X and Y. "short circuit" is not what i'm looking for.

like image 919
user187291 Avatar asked Jan 31 '10 16:01

user187291


1 Answers

As you note, the words you are looking for are not "short-circuit". Short-circuit evaluation means that in the expression

e1 || e2

if expression e1 is evaluated to something representing truth, then it is not necessary to evaluate e2. Both C and Perl use short-circuit evaluation.

I'm aware of the distinction you make in two different flavors of short-circuit OR, but in twenty years of working in programming languages I have never seen these things named. The Perl version is quite popular in dynamic languages, e.g., Icon, Lua, Scheme.

The Perl version is almost expressible in C:

e1 ? e1 : e2

Unfortunately this version may evaluate e1 twice, depending on the optimizer—and if e1 has side effects, or if the compiler can't tell if it might have side effects, then the compiler is required to evaluated it twice. This defect can be fixed by binding the value of e1 to a fresh local variable, but that requires a GNU extension.

The C behavior can be emulated in Perl by

!!(e1 || e2)
like image 50
Norman Ramsey Avatar answered Oct 02 '22 03:10

Norman Ramsey