Reputation: 163347
What's the difference between parameters declared with var
and those declared with out
? How does the compiler treat them differently (e.g., by generating different code, or by changing which diagnostics it issues)? Or do the different modifiers merely allow the programmer to document intended use of the parameters? What effect do the types of the parameters have on the matter?
Upvotes: 61
Views: 27790
Reputation: 119
I read earlier that out parameter is set to default by called function, but today I realized that it is not completely true. Value of out parameter is discarded by called routine, but if that routine does not change its value, caller can still get it initial value, which was assigned before passing to called thread.
For example:
procedure JustNothing(out x : integer);
begin
// do nothing
end;
procedure TestOutVar;
var i : Integer;
begin
i := 100;
JustNothing(i); // after this call, i will still be 100
end;
Upvotes: 1
Reputation: 1875
Slightly late but just for the record, I came across a case where var or out made a big difference.
I was working on a SOAP web service which exported the following method:
function GetUser( out User :TUser ) :TResult;
which was getting imported into C# as the equivalent of
function GetUser( out Result :TResult) :TUser;
when I changed the out to a var it it imported correctly.
I'm guessing that the Delphi SOAP invoker treats the function result as an out parameter and that having two out parameters confuses the Delphi SOAP routines. I'm not sure if there is a workaround to allow you to use out parameters.
Upvotes: 2
Reputation: 43669
There is not much difference, for the compiler that is. See Mason's answer for that.
Semantically, there is a big difference:
var
tells the programmer that the routine could work with its current value,out
tells the programmer that the routine will ignore/discard its current value.Upvotes: 13
Reputation: 84650
A var
parameter will be passed by reference, and that's it.
An out
parameter is also passed by reference, but it's assumed that the input value is irrelevant. For managed types, (strings, Interfaces, etc,) the compiler will enforce this, by clearing the variable before the routine begins, equivalent to writing param := nil
. For unmanaged types, the compiler implements out
identically to var
.
Note that the clearing of a managed parameter is performed at the call-site and so the code generated for the function does not vary with out
or var
parameters.
Upvotes: 55