Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

break condition to OR and AND operators in an IF Statement

The If statement and any other boolean comparison is smart enought to stop at first FALSE value when evaluating A and B and C and D and at first TRUE value when evaluating A or B or C or D.

What is the name of this behavior?
Is this a compiler optimization? If so, there is a way to disable it with some compiler directive?

like image 810
EProgrammerNotFound Avatar asked Sep 03 '13 17:09

EProgrammerNotFound


1 Answers

This is called 'boolean short-circuit evaluation', a form of 'lazy evaluation'.

You can tell the compiler either to use or not to use this feature using compiler directives:

Complete evaluation     Lazy evaluation
{$B+}                   {$B-}
{$BOOLEVAL ON}          {$BOOLEVAL OFF} 

But notice that this isn't only an optimisation, since this feature allows you to write code like

if (length(myarr) > 0) and (myarr[0] = MY_VAL) then

which will work even if myarr[0] doesn't exist. This is rather common, actually.

like image 58
Andreas Rejbrand Avatar answered Sep 28 '22 15:09

Andreas Rejbrand