Passing arguments BY CONTENT to user-defined functions
Though the formal parameters of a user-defined function definition may only be specified
as BY REFERENCE
or BY VALUE
, you can still effectively pass
arguments to a user-defined function BY CONTENT
using the
CONTENT-OF
intrinsic function. To achieve this, you must specify the formal
parameters as BY REFERENCE
in the function definition. On the user-defined function
invocation, the CONTENT-OF
intrinsic function would then be used to wrap each
argument that you would like to be passed effectively BY CONTENT
.
About this task
Identification division.
Function-id. docalc.
Data division.
Linkage section.
1 kind pic x(3).
1 argA pic 999.
1 argB pic v999.
1 res pic 999v999.
Procedure division
using by reference kind argA argB
returning res.
if kind equal "add" then
compute res = argA + argB
end-if
goback.
End function docalc.
Identification division.
Program-id. 'mainprog'.
Environment division.
Configuration section.
Repository.
function content-of intrinsic
function docalc.
Data division.
Working-storage section.
1 result pic 999v999 usage display.
1 arg-1 pic x(3).
1 arg-2 pic 999.
1 arg-3 pic v999.
Procedure division.
move "add" to arg-1
move 10 to arg-2
move 0.23 to arg-3
* arg-1 is effectively BY CONTENT
* arg-2 is BY REFERENCE
* arg-3 is BY REFERENCE
compute result = docalc(content-of(arg-1) arg-2 arg-3)
display "hello from mainprog, result=" result
goback.
End program 'mainprog'.
The CONTENT-OF
intrinsic function produces a temporary copy of the input
argument. The temporary copy is then provided BY REFERENCE
to the user-defined
function and any modifications to the formal parameter within the user-defined function definition
are effectively made to the temporary copy.