Functions in Managed COBOL
method-id TestFunc.
procedure division using by value x as binary-long,
by reference y as binary-long,
output z as binary-long.
add 1 to x, y
move 5 to z
end method.
01 a binary-long value 1.
01 b binary-long value 1.
01 c binary-long. *> c doesn't need initializing
invoke self::TestFunc(value a reference b output c)
*> Or
invoke self::TestFunc(a b c)
display a space b space c
*> sum is an intrinsic function in COBOL
01 total binary-long.
set total to function sum(4 3 2 1) *> returns 10
*> To create a non intrinsic variable argument list function:
method-id MySum.
local-storage section.
01 i binary-long.
procedure division using params nums as binary-long occurs any
returning mysum as binary-long.
perform varying i through nums
add i to mysum
end-perform
end method.
*> then to call it:
method-id main.
local-storage section.
01 i binary-long.
procedure division
set i to self::MySum(1 2 3 4)
display i
end method.
*> COBOL doesn't support optional arguments/parameters.
*> Just create two different versions of the same function.
method-id SayHello.
procedure division using by value nam as string, prefix as string.
display "Greetings, " prefix space nam
end method SayHello.
method-id SayHello.
procedure division using by value nam as string.
invoke self::SayHello(nam "")
end method.
Functions in Java
Portions of these examples were produced by Dr. Frank McCown, Harding University Computer Science Dept, and are licensed under a Creative Commons License.