Thursday, September 25, 2008

Delphi 2009 - Exit

Exit is now very similar to the C++ return keyword where you can supply an optional parameter that is assigned to a functions return value. For example:

function DoStuff(Value: Boolean): Integer;
begin
  if Value then
    Exit(1);

  Result := 0;
end;

6 comments:

Anonymous said...

If I'm not mistaken, this was added in delphi 2007, not 2009.

Anonymous said...

There's no parameters to the "exit" in my 2007'.
How do we query the exit code?

Henrik Carlsen

Anonymous said...

OK. Now I get it. Is the parameter a variant?

Is this possible?

function DoStuff(...): string;
begin
exit('Hello world');
end;

I don't really see the usefulness in the functionality added.

Henrik Carlsen

Anonymous said...

Henrik,

this is possible too.

Adding an exit parameter is e.g. very useful in functions where you have many points where you wish to exit the function early and without the need of coding many nested if..then..else constructs.

Michael

Chris Bensen said...

Yacoding,

This is new to Delphi 2009.

Chris Bensen said...

Henrik,

This is compiler magic. The parameter is the same type as the return value of the function.

Take my example above. In Previous versions of the product you would be required to write:

function DoStuff(Value: Boolean): Integer;
begin
if Value then
begin
Result := 1;
Exit;
end;

Result := 0;
end;

I know someone is going to point out you could write this:

function DoStuff(Value: Boolean): Integer;
begin
if Value then
Result := 1
else
Result := 0;
end;

but that isn't the point because the example just illustrates the new functionality.

I personally will use this in functions where there are many conditions before the final result assignment. Instead of nesting the final result in a bunch of if then statements, there will be a few at the top as failure checks to reduce how deep the rest of the function is nested.

Post a Comment