Jump to content
Steve Maughan

IfThen Oddity...

Recommended Posts

The following code causes an AV:

type

  TFoo = class
  private
    fName: string;
  public
    property Name: string read fName write fName;
  end;

  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses
  StrUtils;

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
var
  Foo: TFoo;
begin
  Foo := nil;
  Form1.Caption := IfThen(assigned(Foo), Foo.Name, '');
end;

The line that cause the AV is the one with the "IfThen" statement. I would have thought this would set the Caption to '' if Foo was not assigned but instead I get an AV. This implies both the True and False expressions are evaluated but I can't see why. Am I missing something obvious? The project is attached. 

 

Delphi 11.1

 

Any insights appreciated. 

 

Steve

IfThenAV.zip

Share this post


Link to post

Function arguments are always evaluated, then passed into the function. This "IfThen" (which I have never seen before), is just a regular function. The compiler has no knowledge that there is no need to evaluate the other arguments if the first one results to False.

  • Like 1

Share this post


Link to post
3 minutes ago, Der schöne Günther said:

Function arguments are always evaluated, then passed into the function. This "IfThen" (which I have never seen before), is just a regular function. The compiler has no knowledge that there is no need to evaluate the other arguments if the first one results to False.

That makes sense. I learn something new every day!

 

Thanks,

 

Steve

Share this post


Link to post

I've never seen it either. Note, there is also System.Math.IfThen

Share this post


Link to post
On 8/16/2022 at 7:18 PM, David Heffernan said:

Why can't we have a conditional operator? 

Because that is not pascal-ish! /s 🙄

P.S. Yes I know about proposals to make it look pascal-ish - I even think we discussed that in another thread already.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×