Skip to main content

Parameter Passing by Reference

As you already know, procedures (including user-defined functions) accept parameters. By default, these parameters are passed by value. That means that the procedure can use the value of a variable passed into it, but can't modify the value of the variable itself. The first part of the example, $$dblbyval, uses the num variable to compute its double, but the num variable, outside the procedure, is not changed.

Like other languages, ObjectScript also allows you to pass parameters by reference, which means that the procedure can modify the value of the variable. You place a dot before the variable name when calling the procedure. The dblbyref1 procedure changes num into its double, but only because of the dot preceding num. Passing parameters to a procedure by reference only works if you call the procedure correctly, preceding these parameters with a dot. The dblbyref2 procedure returns the double of num by creating a new variable, called result.

SAMPLES>do ^passbyref

Enter a number: 3
3 doubled is: 6
3 doubled is: 6
6 doubled again is: 12
SAMPLES>

The passbyref.mac code:

passbyref ; passing parameters by value and reference
    ; pass by value
    read !, "Enter a number: ", num
    set dblnum = $$dblbyval( num )
    write !, num, " doubled is: ", dblnum

    ; num passed IN and OUT by reference
    write !, num
    do dblbyref1( .num )
    write " doubled is: ", num

    ; num passed IN by value
    ; result passed OUT by reference
    do dblbyref2(num, .result)
    write !, num, " doubled again is: ", result
    quit

dblbyval(anynum) PUBLIC
    { quit anynum * 2 }

dblbyref1(anynum) PUBLIC
    { set anynum = anynum * 2
    quit }

dblbyref2(anynum, double) PUBLIC
    { set double = anynum * 2
    quit }
FeedbackOpens in a new tab