Using intrinsic functions (built-in functions)
Some high-level programming languages have built-in functions that you can reference in your program as if they were variables that have defined attributes and a predetermined value. In COBOL, these functions are called intrinsic functions. They provide capabilities for manipulating strings and numbers.
Because the value of an intrinsic function is derived
automatically at the time of reference, you do not need to define
functions in the DATA DIVISION
. Define only the nonliteral
data items that you use as arguments. Figurative constants are not
allowed as arguments.
A function-identifier is
the combination of the COBOL reserved word FUNCTION
followed
by a function name (such as Max
), followed by any
arguments to be used in the evaluation of the function (such as x
, y
, z
).
For example, the groups of highlighted words below are function-identifiers:
Unstring Function Upper-case(Name) Delimited By Space
Into Fname Lname
Compute A = 1 + Function Log10(x)
Compute M = Function Max(x y z)
A function-identifier represents both the invocation
of the function and the data value returned by the function. Because
it actually represents a data item, you can use a function-identifier
in most places in the PROCEDURE DIVISION
where a
data item that has the attributes of the returned value can be used.
The
COBOL word function
is a reserved word, but the function-names
are not reserved. You can use them in other contexts, such as for
the name of a data item. For example, you could use Sqrt
to
invoke an intrinsic function and to name a data item in your program:
Working-Storage Section.
01 x Pic 99 value 2.
01 y Pic 99 value 4.
01 z Pic 99 value 0.
01 Sqrt Pic 99 value 0.
. . .
Compute Sqrt = 16 ** .5
Compute z = x + Function Sqrt(y)
. . .
A function-identifier represents a value that is of one of these types: alphanumeric, national, numeric, or integer. You can include a substring specification (reference modifier) in a function-identifier for alphanumeric or national functions. Numeric intrinsic functions are further classified according to the type of numbers they return.
The
functions MAX
and MIN
can
return either type of value depending on the type of arguments you
supply.
Functions
can reference other functions as arguments provided that the results
of the nested functions meet the requirements for the arguments of
the outer function. For example, Function Sqrt(5)
returns
a numeric value. Thus, the three arguments to the MAX
function
below are all numeric, which is an allowable argument type for this
function:
Compute x = Function Max((Function Sqrt(5)) 2.5 3.5)