Recent

Author Topic: IF statement testing for NIL  (Read 324 times)

speter

  • New Member
  • *
  • Posts: 41
IF statement testing for NIL
« 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.


Sieben

  • Full Member
  • ***
  • Posts: 144
Re: IF statement testing for NIL
« Reply #1 on: October 28, 2020, 01:14:49 am »
Have a look at the {$B} compiler directive:

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

{$B-} is default setting, so that Form2.Visible would never be tested if (Form2 <> nil) already evaluates to False.
Lazarus 2.0.10, FPC 3.2.0, .deb install on Ubuntu Xenial 32

speter

  • New Member
  • *
  • Posts: 41
Re: IF statement testing for NIL
« Reply #2 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.

PascalDragon

  • Hero Member
  • *****
  • Posts: 2429
  • Compiler Developer
Re: IF statement testing for NIL
« Reply #3 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).

speter

  • New Member
  • *
  • Posts: 41
Re: IF statement testing for NIL
« Reply #4 on: October 28, 2020, 11:32:19 am »
Thanks.

cheers
S.

 

TinyPortal © 2005-2018