break condition to OR and AND operators in an IF Statement
Asked Answered
A

1

5

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?

Almanac answered 3/9, 2013 at 17:48 Comment(3)
Why would you want to disable this? It's normal functionality of the if statement.Datura
@JerryDodge sometimes short-circuit evaluation will get you in trouble with logic that might be unexpected if you aren't completely aware of it, so the option to disable it is offered. If you don't (or can't) plan it out so not evaluating conditions won't cause problems, it can come back to bite you.Inner
@JerryDodge Maybe the functions he uses in the if condition have other functionality he wishes to take effect? (It would be bad design though it could be something hardly avoided if i.e. he has some 3rd party code pieces there.)Waldenses
A
14

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.

Abott answered 3/9, 2013 at 17:52 Comment(3)
You can also set it through the Project Options in the IDE. If you really wanted to shoot yourself in the foot, you have the ability to set it differently for each build configuration.Exemplary
@MatheusFreitas can you share why do you need this? Maybe the functions you use in the if condition have other functionality you wish to take effect? Please note, that having functions with side effects AND return values is a bad coding practice. (If the returned value does not serve as an error report.) If so, can't you save the function results in boolean buffers and use the buffers in the if header instead?Waldenses
@MatheusFreitas in this case, sorry for the inconvenience. But still... it could be done, but it is a bad practice to do so. :DWaldenses

© 2022 - 2024 — McMap. All rights reserved.