Steve Maughan 26 Posted August 16, 2022 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
Der schöne Günther 316 Posted August 16, 2022 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. 1 Share this post Link to post
Steve Maughan 26 Posted August 16, 2022 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
Stano 143 Posted August 16, 2022 I've never seen it either. Note, there is also System.Math.IfThen Share this post Link to post
David Heffernan 2345 Posted August 16, 2022 IfThen as a function sucks big time. Why can't we have a conditional operator? 3 Share this post Link to post
Stefan Glienke 2006 Posted August 18, 2022 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
Alexander Elagin 143 Posted August 18, 2022 Oxygene from RemObjects makes it look pascalish enough: var lDescriptiveText := if x < 10 then 'less than ten' else 'ten or more'; https://docs.elementscompiler.com/Oxygene/Expressions/If/ Share this post Link to post