SAMPro
SAMPro

Reputation: 1109

Bypass function "out" parameters

Some functions need a variable to send out a value. But sometimes I don't need that value and don't want to define a variable to use it as function out parameter. Like this:

procedure test(out SomeVar: string);
begin
   //...
end;

I want to execute this safely:

test; 

Upvotes: 3

Views: 833

Answers (3)

Arnaud Bouchez
Arnaud Bouchez

Reputation: 43053

You can overload the procedure:

procedure test(out SomeVar: string); overload;
begin
   //...
end;

procedure test; overload; inline;
var dummy: string;
begin
  test(dummy);
end;

Note the inline keyword, available since Delphi 2005 AFAIR.

What I usually do is to use a pointer instead of out parameter:

procedure test(SomeVarP: PString=nil); 
begin
   if SomeVarP<>nil then
     SomeVarP^ := ....
end;

As such you can use:

var s: string;

test;
test(@s);

Upvotes: 4

Remy Lebeau
Remy Lebeau

Reputation: 597885

Use a pointer:

procedure test(SomeVar: PString = nil);
begin
  if SomeVal <> nil then SomeVar^ := '';
  //...
  if SomeVal <> nil then SomeVar^ := ...;
end;

test; 

var
  s: string;

test(@s); 

Upvotes: 2

Blorgbeard
Blorgbeard

Reputation: 103525

You can create a wrapper:

procedure test(); overload;
var
    SomeVar : string;
begin
    test(SomeVar);
end;

Note: You'll also have to mark the other version with overload, or you can call your wrapper something other than test, and remove the overload.

Another option: declare a dummy variable somewhere (at the top of your unit, maybe):

var 
  DummyStr : string;

Then you don't have to declare a new variable every time you want to call the function.

test(DummyStr);

Upvotes: 6

Related Questions