Lazarus

Programming => General => Topic started by: speter on October 28, 2020, 01:07:31 am

Title: IF statement testing for NIL
Post by: speter on October 28, 2020, 01:07:31 am
G'Day Folks,

When dealing with 2 (or more) forms I often have code like:

Code: Pascal  [Select][+][-]
  1. if (Form2 <> nil) and Form2.visible then
  2.   Form2.dosomething;

I believe it is _safer_ to write:

Code: Pascal  [Select][+][-]
  1. if (Form2 <> nil) then
  2.   if Form2.visible then
  3.     Form2.dosomething;

to make sure form2.visible is not tested if form2 is actually nil.

Does it matter? Is the first technique safe or can the compiler optimisation make this dangerous!?

cheers
S.

Title: Re: IF statement testing for NIL
Post by: Sieben on October 28, 2020, 01:14:49 am
Have a look at the {$B} compiler directive:

https://wiki.freepascal.org/$boolEval (https://wiki.freepascal.org/$boolEval)

{$B-} is default setting, so that Form2.Visible would never be tested if (Form2 <> nil) already evaluates to False.
Title: Re: IF statement testing for NIL
Post by: speter on October 28, 2020, 01:29:23 am
Sieben, thank you for the quick reply!

Interestingly the page you reference includes the statement:
Quote
Such implicit “removal” of code, that the order one writes expressions in is relevant, is depreciated by Pascal.
and supports the if-if form over the if-and form; though it states - as you write - that
Quote
FPC uses shortcut Boolean
which kind of muddies the whole question. :)

cheers
S.
Title: Re: IF statement testing for NIL
Post by: PascalDragon on October 28, 2020, 09:18:41 am
Interestingly the page you reference includes the statement:
Quote
Such implicit “removal” of code, that the order one writes expressions in is relevant, is depreciated by Pascal.
and supports the if-if form over the if-and form; though it states - as you write - that
Quote
FPC uses shortcut Boolean
which kind of muddies the whole question. :)

If I were you I'd ignore that statement whoever wrote that. FPC uses shorthand Boolean evaluation by default and it will stay like that (and most users like it that way anyway) especially as enough code out there relies on it.

So to answer your question: doing the check in one statement is safe as long as shorthand evaluation of Boolean expressions is enabled (which is the default).
Title: Re: IF statement testing for NIL
Post by: speter on October 28, 2020, 11:32:19 am
Thanks.

cheers
S.
TinyPortal © 2005-2018