var, out and const in Delphi function parameter decoration

(1) var modifier

Adding var is address transfer, which will modify the original variable

where

  s: string;

begin

  S := 'Hello';

  ChangeSVar(s);

  ShowMessage(S);

end;

// ChangeSVar definition

procedure TForm1.ChangeSVar (var A: string);

begin

  A := A + 'World';

end;

The above will output Hello World, because it is an address, and the original A is modified

(2) without any modifiers

where

  s: string;

begin

  S := 'Hello';

  ChangeS(s);

  ShowMessage(S);

end;

// ChangeS definition

procedure TForm1.ChangeS(A: string);

begin

  A := A + 'World';

end;

The above will output Hello, because the method ChangeS actually creates a new A, and the output is still the original A, and the value has not changed.

(3) out modifier

where

  s: string;

begin

  S := 'Hello';

  ChangeSOut(s);// The value of S is 'Hello,' instead of 'Hello, World'!, the original value of S in the process Hello is discarded

  ShowMessage(S);

end;

// ChangeSOut definition

procedure TForm1.ChangeSOut(out A: string);

begin

  A := A + 'World';

end;

The above will output World, out just accepts the returned value, any input to out will be ignored. At the same time, the actual parameters passed to the procedure by out do not have to be initialized, such as the call to ChangeSOut:

Where

  Tmp: string;

Begin

  ChangeSOut(Tmp);//Compilation can also be done through

End;

(4) Const modifier

Parameters modified by Const are not allowed to be modified after being passed in

If the parameters are modified during the process, an error will be reported, for example:

Procedure xxxx.TestConst(const A: String);

Begin

  A := 'ss'; //Attempt to modify the parameters modified by const, an error will be reported

End;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324983396&siteId=291194637