Sign in

docs RPG Reference

Built-in Functions

Built-in Functions

Built-in functions are similar to operation codes in that they perform operations on data you specify. Built-in functions can be used in expressions. Additionally, constant-valued built-in functions can be used in named constants. These named constants can be used in any specification.

All built-in functions have the percent symbol (%) as their first character. The syntax of built-in functions is:

function-name{(argument{:argument...})}

Arguments for the function may be variables, constants, expressions, a prototyped procedure, or other built-in functions. An expression argument can include a built-in function. The following example illustrates this.

Figure 1. Built-in Function Arguments Example

CL0N01Factor1+++++++Opcode(E)+Extended-factor2++++++++++++++++++++++++++
 *
 * This example shows a complex expression with multiple
 * nested built-in functions.
 *
 * %TRIM takes as its argument a string.  In this example, the
 * argument is the concatenation of string A and the string
 * returned by the %SUBST built-in function.  %SUBST will return
 * a substring of string B starting at position 11 and continuing
 * for the length returned by %SIZE minus 20.  %SIZE will return
 * the length of string B.
 *
 * If A is the string '     Toronto,' and B is the string
 * '  Ontario, Canada            ' then the argument for %TRIM will
 * be '     Toronto, Canada    ' and RES will have the value
 * 'Toronto, Canada'.
 *
C                   EVAL      RES = %TRIM(A + %SUBST(B:11:%SIZE(B) - 20))

See the individual built-in function descriptions for details on what arguments are allowed.

Unlike operation codes, built-in functions return a value rather than placing a value in a result field. The following example illustrates this difference.

Figure 2. Built-in Function Example

CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
 *
 * In the following example, CITY contains the string
 * 'Toronto, Ontario'.  The SCAN operation is used to locate the
 * separating blank, position 9 in this illustration.  SUBST
 * places the string 'Ontario' in field TCNTRE.
 *
 * Next, TCNTRE is compared to the literal 'Ontario' and
 * 1 is added to CITYCNT.
 *
C     ' '           SCAN      CITY          C
C                   ADD       1             C
C                   SUBST     CITY:C        TCNTRE
C    'Ontario'      IFEQ      TCNTRE
C                   ADD       1             CITYCNT
C                   ENDIF
 *
 * In this example, CITY contains the same value, but the
 * variable TCNTRE is not necessary since the %SUBST built-in
 * function returns the appropriate value.  In addition, the
 * intermediary step of adding 1 to C is simplified since
 * %SUBST accepts expressions as arguments.
 *
C     ' '           SCAN      CITY          C
C                   IF        %SUBST(CITY:C+1) = 'Ontario'
C                   EVAL      CITYCNT = CITYCNT+1
C                   ENDIF

Note that the arguments used in this example (the variable CITY and the expression C+1) are analogous to the factor values for the SUBST operation. The return value of the function itself is analogous to the result. In general, the arguments of the built-in function are similar to the factor 1 and factor 2 fields of an operation code.

Another useful feature of built-in functions is that they can simplify maintenance of your code when used on the definition specification. The following example demonstrates this feature.

Figure 3. Simplified Maintenance with Built-in Functions

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++++++++
 *
 * In this example, CUSTNAME is a field in the
 * externally described data structure CUSTOMER.
 * If the length of CUSTNAME is changed, the attributes of
 * both TEMPNAME and NAMEARRAY would be changed merely by
 * recompiling.  The use of the %SIZE built-in function means
 * no changes to your code would be necessary.
 *
D CUSTOMER      E DS
D                 DS
D TEMPNAME                            LIKE(CUSTNAME)
D NAMEARRAY                      1    OVERLAY(TEMPNAME)
D                                     DIM(%SIZE(TEMPNAME))

Built-in functions can be used in expressions on the extended factor 2 calculation specification and with keywords on the definition specification. When used with definition specification keywords, the value of the built-in function must be known at compile time and the argument cannot be an expression.

The following table lists the built-in functions, their arguments, and the value they return.

Table 1. Built-In Functions

NameArgumentsValue Returned
%ABSnumeric expressionabsolute value of expression
%ADDRvariable name {: *DATA}address of variable, or address of the data portion of a variable-length variable
%ALLOCnumber of bytes to allocatepointer to allocated storage
%BITANDcharacter, numericbit wise ANDing of the bits of all the arguments
%BITNOTcharacter, numericbit-wise reverse of the bits of the argument
%BITORcharacter, numericbit-wise ORing of the bits of all the arguments
%BITXORcharacter, numericbit-wise exclusive ORing of the bits of the two arguments
%CHAR* character, graphic, UCS-2 expression { : ccsid } * numeric expression * date, time, timestamp expression {: date, time, or timestamp format}* value in character format with the specified CCSID * value in character format with the job CCSID * value in character format with the job CCSID
%CHARCOUNTstring expressionthe number of natural characters in the string
%CHECKcomparator string:string to be checked{:start position}first position of a character that is not in the comparator string, or zero if not found
%CHECKRcomparator string:string to be checked{:start position}last position of a character that is not in the comparator string, or zero if not found
%CONCATseparator : string1 { : string2 { : string3 … } }Operands 2 to N separated by the separator
%CONCATARRseparator : array}Elements of the array separated by the separator
%DATAdocument { : options }not applicable
%DATE{value {: date format}}the date that corresponds to the specified value, or the current system date if none is specified
%DAYSnumber of daysnumber of days as a duration
%DEC* numeric expression {:digits:decpos} * character expression: digits:decpos * date, time or timestamp expression {:format}value in packed numeric format
%DECHnumeric or character expression: digits:decposhalf-adjusted value in packed numeric format
%DECPOSnumeric expressionnumber of decimal digits
%DIFFdate or time expression: date or time expression: unit {:fractional seconds}difference between the two dates, times, or timestamps in the specified unit
%DIVdividend: divisorthe quotient from the division of the two arguments
%EDITCnon-float numeric expression:edit code {:*CURSYM*ASTFILL
%EDITFLTnumeric expressioncharacter external display representation of float
%EDITWnon-float numeric expression:edit wordstring representing edited value
%ELEM 1array, table, or multiple occurrence data structure namenumber of elements or occurrences
%EOF{file name}‘1’ if the most recent cycle input, read operation, or write to a subfile (for a particular file, if specified) ended in an end-of-file or beginning-of-file condition.
‘0’ otherwise. Note: The CHAIN, OPEN, SETGT, and SETLL operations also affect %EOF when a parameter is specified. See %EOF (Return End or Beginning of File Condition).
%EQUAL{file name}‘1’ if the most recent SETLL (for a particular file, if specified) or LOOKUP operation found an exact match
’0’ otherwise
%ERROR’1’ if the most recent operation code with extender ‘E’ specified resulted in an error
’0’ otherwise
%FIELDS* list of fields to be updated * list of subfields for sortingnot applicable
%FLOATnumeric or character expressionvalue in float format
%FOUND{file name}‘1’ if the most recent relevant operation (for a particular file, if specified) found a record (CHAIN, DELETE, SETGT, SETLL), an element (LOOKUP), or a match (CHECK, CHECKR, SCAN)
‘0’ otherwise
%GENgenerator { : options }not applicable
%GRAPHcharacter, graphic, or UCS-2 expression { : ccsid }value in graphic format with specified CCSID
%HANDLERhandling procedure : communication areanot applicable
%HIVALvariablehighest possible value of the variable
%HOURSnumber of hoursnumber of hours as a duration
%INTnumeric or character expressionvalue in integer format
%INTHnumeric or character expressionhalf-adjusted value in integer format
%KDSdata structure containing keys {: number of keys}not applicable
%LENany expressionlength in digits or characters
%LEFTstring : lengthleftmost characters
%LISTitem1 { : item2 { : item3 … } }array created from the operands
%LOOKUPxxargument: array{:start index {:number of elements}}array index of the matching element
%LOVALvariablelowest possible value of the variable
%LOWERstring{:start{:length}}string, with the substring converted to lower case
%MAXitem1 : item2 { : item3 { : item4 … } }maximum value of the operands
%MAXARRarray { : start-element { : number-of-elements } }index of the maximum value in the array
%MINitem1 : item2 { : item3 { : item4 … } }minimum value of the operands
%MINARRarray { : start-element { : number-of-elements } }index of the minimum value in the array
%MINUTESnumber of minutesnumber of minutes as a duration
%MONTHSnumber of monthsnumber of months as a duration
%MSECONDSnumber of microsecondsnumber of microseconds as a duration
%MSGmessage ID : message file { : replacement text }not applicable
%NULLINDnull-capable field namevalue in indicator format representing the null indicator setting for the null-capable field
%OCCURmultiple-occurrence data structure namecurrent occurrence of the multiple-occurrence data structure
%OMITTEDprocedure-interface parameter namewhether *OMIT was passed for the parameter
%OPENfile name’1’ if the specified file is open
’0’ if the specified file is closed
%PADDRprocedure or prototype nameaddress of procedure or prototype
%PARMSnonenumber of parameters passed to procedure
%PARMNUMprocedure-interface parameter namenumber of a procedure-interface parameter
%PARSERparser { : options }not applicable
%PASSEDprocedure-interface parameter namewhether the parameter was passed and not omitted
%PROC{*OWNER*ONEXIT}
%RANGEitem1 : item2not applicable
%REALLOCpointer: numeric expressionpointer to allocated storage
%REMdividend: divisorthe remainder from the division of the two arguments
%REPLACEreplacement string: source string {:start position {:source length to replace}}string produced by inserting replacement string into source string, starting at start position and replacing the specified number of characters
%RIGHTstring : lengthrightmost characters
%SCANsearch argument:string to be searched{:start position{:length}}first position of search argument in string or zero if not found
%SCANRsearch argument:string to be searched{:start position{:length}}last position of search argument in string or zero if not found
%SCANRPLscan string: replacement string: source string {:scan start position {:scan length}}string produced by replacing scan string by replacement string in source string, with the scan starting at start position for the specified length
%SECONDSnumber of secondsnumber of seconds as a duration
%SHTDN’1’ if the system operator has requested shutdown
’0’ otherwise
%SIZE 1variable, array, or literal {:* ALL}size of variable or literal
%SPLITstring{:separators}array of substrings
%SQRTnumeric valuesquare root of the numeric value
%STATUS{file name}0 if no program or file error occurred since the most recent operation code with extender ‘E’ specified
most recent value set for any program or file status, if an error occurred
if a file is specified, the value returned is the most recent status for that file
%STRpointer{:maximum length}characters addressed by pointer argument up to but not including the first x’00’
%SUBARRarray name:start index{:number of elements}array subset
%SUBDTdate or time expression: unitan unsigned numeric value that contains the specified portion of the date or time value
%SUBDTdate or time expression: unit { digits : { fractional seconds}}
%SUBSTstring:start{:length}substring
%TARGETprogram or procedure { : offset }not applicable
%THISthe class instance for the native method
%TIME{value {: time format}}the time that corresponds to the specified value, or the current system time if none is specified
%TIMESTAMP{(value {: timestamp format {: fractional seconds}})}the timestamp that corresponds to the specified alphanumeric or numeric value, or the current system timestamp if none is specified
%TIMESTAMP{(value {: fractional seconds})}the timestamp that corresponds to the specified date or timestamp value, or the current system timestamp if none is specified
%TLOOKUPxxargument: search table {: alternate table}‘*ON’ if there is a match
’*OFF’ otherwise
%TRIMstring {: characters to trim}string with left and right blanks or specified characters trimmed
%TRIMLstring {: characters to trim}string with left blanks or specified characters trimmed
%TRIMRstring {: characters to trim}string with right blanks or specified characters trimmed
%UCS2character, graphic, or UCS-2 expression { : ccsid }value in UCS-2 format with specified CCSID
%UNSnumeric or character expressionvalue in unsigned format
%UNSHnumeric or character expressionhalf-adjusted value in unsigned format
%UPPERstring{:start{:length}}string, with the substring converted to upper case
%XFOOTarray expressionsum of the elements
%XLATEfrom-characters: to-characters: string {: start position}the string with from-characters replaced by to-characters
%XMLxml document { : options }not applicable
%YEARSnumber of yearsnumber of years as a duration
Note: 1. Complex qualified names are not allowed.