Value and Variable Parameters

Most parameters are either value parameters (the default) or variable (var) parameters. Value parameters are passed by value, while variable parameters are passed by reference. To see what this means, consider the following functions.

function DoubleByValue(X: Integer): Integer; // X is a value parameter begin

function DoubleByRef(var X: Integer): Integer; // X is a variable parameter begin

These functions return the same result, but only the second one - DoubleByRefcan change the value of a variable passed to it. Suppose we call the functions like this:

J := DoubleByValue(I); // J = 8, I = 4 W := DoubleByRef(V); // W = 8, V = 8

end;

After this code executes, the variable I, which was passed to DoubleByValue, has the same value we initially assigned to it. But the variable V, which was passed to DoubleByRef, has a different value.

A value parameter acts like a local variable that gets initialized to the value passed in the procedure or function call. If you pass a variable as a value parameter, the procedure or function creates a copy of it; changes made to the copy have no effect on the original variable and are lost when program execution returns to the caller.

A variable parameter, on the other hand, acts like a pointer rather than a copy. Changes made to the parameter within the body of a function or procedure persist after program execution returns to the caller and the parameter name itself has gone out of scope.

Even if the same variable is passed in two or more var parameters, no copies are made. This is illustrated in the following example.

procedure AddOne(var X, Y: Integer); begin

After this code executes, the value of I is 3.

If a routine's declaration specifies a var parameter, you must pass an assignable expression - that is, a variable, typed constant (in the {$J+} state), dereferenced pointer, field, or indexed variableto the routine when you call it. To use our previous examples, DoubleByRef(7) produces an error, although

DoubleByValue(7) is legal.

Indexes and pointer dereferences passed in var parameters - for example, DoubleByRef(MyArray [I]) - are evaluated once, before execution of the routine.

Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook


Post a comment