Delphi 2007 Handbook




Essential Pascal




social web book








November 9, 2007

Handbook Note 37/113: Assigning Result

Note 37 of 113 of Delphi 2007 Handbook

Note 37: You can write the code also with the classic if-then-else statement, rather then using the initial assignment to the Result:

      if ItemIndex >= 0 then
      
Result := Items [ItemIndex]
else
Result := '';

I tend to prefer setting uninitialized stack values, including local variables and results, even when it is not strictly required, because failing to do so at times results in hard-to-track errors.


To make the note understandable, here is the actual code in the book. Which style do you prefer?

Result := '';
if ItemIndex >= 0 then
Result := Items [ItemIndex];

This blog post is part of my "113 Delphi 2007 Handbook Notes" blogging project, to promote my new Delphi book.





 

3 Comments

Handbook Note 37/113 Assigning Result 

Usually I prefer the second one.

It might be interesting to analyze which of these is 
faster. The 1st style calls LStrClr, the 2nd style 
avoids a jmp instruction. Well, I guess the 2nd style 
produces the faster code when returning a class or 
Integer.
Comment by Benji [] on November 9, 21:12

Handbook Note 37/113 Assigning Result 

> Which style do you prefer?

That depends on if I want speed or less typing.
Comment by Andreas Hausladen [] on November 9, 21:50

Handbook Note 37/113 Assigning Result 

I prefer the if/then/else version for the fact that
it'll be faster (by a tiny, miniscule fraction of a
nanosecond :-)), since you'll only assign a value to
result once and not (perhaps) twice.

But in other cases (more advanced than the example) I
also use a pre-initialization of Result.

I even use Result in FOR/IN statements, like the
following:

FUNCTION IndexOf(CONST ARR : TArray ; CONST STR :
ShortString) : TRecord;
  BEGIN
    FOR Result IN ARR DO IF Result.Name=STR THEN EXIT;
    Result:=NIL
  END;
Comment by Keld R. Hansen [http://www.heartware.dk] on November 10, 18:26


Post Your Comment

Click here for posting your feedback to this blog.

There are currently 0 pending (unapproved) messages.