NATURAL EXPRESSIONS


Expressions in RPG are specified in traditional mathematical infix notation. This kind of expression syntax is sometimes referred to as natural expression. Natural expressions allow basic mathematics to be written with RPG in a form similar to traditional mathematics. Bertrand Russell, the British philosopher and mathematician, once said, "Mathematics may be defined as the subject in which we never know what we are talking about, nor whether what we are saying is true." (Andrews, Robert. The Columbia Dictionary of Quotations. New York: Columbia University Press, 1993.)

In previous versions of RPG, the programmer always knew the outcome of an expression because only fixed-format, single-operator expressions were permitted. With natural expression support in RPG IV, programmers can write as complex or simple an algorithm as needed. As for complex algorithms, to paraphrase Bertrand, the programmer that follows the program author might never know what is expressed or if it is true. So write as basic an expression as possible.

Expressions are made up of operands and operators. Operands typically are data such as fields or numeric literals. Operators are mathematical symbols such as + (addition), - (subtraction), * (multiplication), or / (division); and conjuncts such as AND, OR, and NOT. The operators supported in RPG natural expressions are those listed in Table 3.1.

Table 3.1: Expression Operators

Operator

Type

Description

+

Unary

Indicates positive numerical value

-

Unary

Indicates negative numerical value

NOT

Unary

Opposite of evaluated result

+

Binary (alpha)

Concatenation of two character strings

+

Binary (numeric)

Addition

-

Binary (numeric)

Subtraction

*

Binary

Multiplication

/

Binary

Division

**

Binary

Exponentiation (powers and roots)

=

Comparison

Equal

=

Assignment

Set values equal

>=

Comparison

Greater than or equal

>

Comparison

Greater than

<=

Comparison

Less than or equal

<

Comparison

Less than

<>

Comparison

Not equal

AND

Logical

AND conjunction comparison

OR

Logical

OR conjunction comparison

Priority of Operators

Expressions are parsed and then evaluated in a defined order. To ensure that the equation always results in the same value, a precedence of the operations is applied. Fortunately, this precedence is the same as that used by most other programming languages as well as mathematics. Table 3.2 lists the priority of the operators used in expressions in RPG.

Table 3.2: Order of Evaluation of Operators

Priority

Operator

Description

1

()

Parentheses

2

Functions

Built-in functions or procedure functions

3

Unary operators

Unary +, -

3

Logical not

NOT

4

**

Powers and roots

5

* /

Multiplication and division

6

Binary operators

Binary +, -,

7

Comparison

Comparison operators, =, >=, >, <=, <,

8

Logical operators

Logical AND, logical OR

9

=

Assignment

The priority of parentheses and built-in functions is interpreted as meaning that the operations inside the parentheses are performed independently of the operations outside the parentheses. Use parentheses for clarity or when the priority of the equation is uncertain. Parentheses can be used to override the priority. Hence, parentheses can force an addition operation to be performed before a multiplication operation.

The order of evaluation of an expression is important and is established with traditional mathematical precedence rules.

The power function ** is used for exponentiation. Mathematical rules state that, if a value is raised to the power of n, it is multiplied by itself n times. For example, 2**3 would result in 2*2*2, which evaluates to 8.

Mathematical rules also state that, if a value is raised to the power of 1/n (i.e., "one over n"), the result is the nth root of the value. For example, 16**(1/4) evaluates to the 4th root of 16, or 2. Table 3.3 lists a few examples of equations that use powers and roots.

Table 3.3: Powers and Roots Syntax

Equation

Description

4**2

Result is 4 squared or 4x4 (16).

4**.5

Result is the square root of 4 (2).

27**(1/3)

Finds the cube root of 27 (3).

16**(1/2)

Finds the square root of 16 (4).

Expressions can be categorized into three types, Boolean, numeric, and string. An expression is any list of tokens that represents a value, either a character string or numeric value, or an operator (see Table 3.1). In other words, any character string or numeric value, be it a simple number or complex math formula, is an expression.

RPG support for natural expressions is similar to that of CL, BASIC, COBOL, C++, and PL/I. Expressions can be used in the extended factor 2 of the alternate calculation specification, and in the keyword section of the definition specification. Expressions can be used in assignment statements, compare statements, or in declarations.

Expressions, known as tokens, are made up of literal values, numbers, fields, and symbols. Symbols are used to perform operations on the various values. An expression can be as simple as the number 12 or as complex as the equation: (4*PI)*R**2.

Expression Continuation

To continue an expression, place the next token of the expression on the next line in the extended factor 2 or the function/keyword area of the definition specification.

To continue a quoted character string, use either a + (plus) or - (minus) sign to continue the string. This directs the compiler to concatenate the value together either on the first nonblank position when using the + sign or the first position of the extended factor 2 or function/keyword area when using the - sign.

Expressions in Assignment Statements

When one value is assigned to another, the EVAL and EVALR operation codes are used. These operations copy the value on the right side of the equal sign, known as the r-value, to the variable on the left of the equal sign, known as the l-value. The assignment must result in an r-value and an l-value that match. In other words, if the l-value is character, then the r-value must result in a character value.

The EVAL and EVALR operations work with all types of expressions. When used with character expressions, EVAL copies the value left justified. EVALR copies the value right justified.

The l-value can be an expression, but only when it is a character variable or an array name with an index value. The %SUBST() built-in function can be used as the l-value. In addition, numeric expressions can be used on the starting position and the length of the %SUBST() function. When an array index is specified, the index may be a literal, a field, or an expression. Figure 3.1 contains a sample of several expressions used in assignment statements.

start figure

 .....CSRn01Factor1+++++++OpCode(ex)Factor2++++++++++++++++++++++++++++++++++++++ 0001 C                   EVAL       A = B + C 0002 C                   EVAL       Amt_Due = Amt_Due - Amt_Paid 0003 C                   EVAL       PI = 3.1415926 0004 C                   EVAL       Area = 4 * PI * Radius ** 2 0005 C                   EVAL       Message = 'RPGIV is cool!' 0006 C                   EVAL       %subst(comp_name : start+3 : start+6) = 'Q38' 0007 C                   EVAL       ptrData = %ADDR(comp_name) 0008 C                   EVAL       Presidents(I + 1) = 'George ' 0009 C                                + 'Washington' 0010 C                   EVAL       *INLR = (%EOF(CUSTMAST) or %EOF(ITEMMAST)) 0011 C                   EVAL       *IN32 = Amount > 100 and (Price - Cost) < 25.50 

end figure

Figure 3.1: Examples of assignment expressions.

In Figure 3.1, line 1 computes the sum of B plus C and stores the result in A. In line 2, the AMT_DUE field is reduced by AMT_PAID. In line 3, the field named PI receives the value of 3.1415926. In line 4, the area of a sphere is computed as 4*PI*R2.

Line 5 copies a character string expression to the field named MESSAGE. Line 6 copies the character string expression 'Q38' to a substring location of the COMP_NAME field.

Line 7 retrieves the address of the field COMP_NAME and copies it into the pointer variable named PTRDATA. Line 8 concatenates the string 'George ' 'Washington' into 'George Washington' and copies it into an array element of the PRESIDENTS array. The element index is calculated from the expression I+1.

Line 10 is a Boolean expression. Indicator LR is set on if the end-of-file condition exists for either the CUSTMAST or ITEMMAST file. Line 11 sets on indicator 32 if the AMOUNT field is greater than 100 and the difference between PRICE and COST is less than 25.50.

Expressions in Compare Statements

The RPG operations DOW, DOU, IF, FOR, and WHEN allow the use of expressions as compare statements. Expressions used with these operations do not assign their result to a field. Rather, the values are used to compare one value to another.

The DOW, DOU, IF, FOR, and WHEN operations have identical support for expressions. Figure 3.2 illustrates various conditional expressions.

start figure

 .....CSRn01Factor1+++++++OpCode(ex)Factor2+++++++Result++++++++Len++DcHiLoEq.... .....CSRn01..............OpCode(ex)Extended-factor2+++++++++++++++++++++++++++++ 0001 C                   if         A = B 0002 C                   if         Amt_Due > 10000 and DaysOvrDue >= 30 0003 C                   if         (Price - Cost) / Price < 10 or 0004 C                               Cost = 0 0005 C                   select 0006 C                   when       *IN01 = *ON 0007 C                   DOU        *INLR 0008 C                   read       Customer                              LR 0009 C                   endDo 0010 C                   endSL 0011 C                   Endif 0012 C                   Endif 0013 C                   Endif 

end figure

Figure 3.2: Expressions on conditional statements.

In Figure 3.2, line 1 is a basic comparison expression. When the fields A and B are equal, the condition is considered TRUE. When they are not equal, the condition is FALSE.

Line 2 compares the AMT_DUE field to 10000. If AMT_DUE is greater than 10,000, it then evaluates the next condition. If DAYSOVRDUE is greater than or equal to 30, the entire conditional expression is considered true. If either the first condition or second condition is not true, the entire condition is considered false.

Lines 3 and 4 perform inline math. The equation of PRICE minus COST is performed first. The parentheses override the normal order of evaluation. The result of PRICE-COST is stored in a temporary result, and that result is divided by PRICE. The result of the division operation is stored in another temporary result. The next thing that happens is the comparison of the second temporary result to the number 10. If the result is less than 10, the condition is true. The OR operator is bypassed for now and the evaluation of COST = 0 is performed. If COST is equal to 0, that portion of the expression is true. The OR operator is used to test whether the left or right side operands evaluate to true. If either side is true, the condition is considered true.

Line 6 performs a WHEN (inline case), testing indicator 01 (*IN01) for an ON condition. If the indicator is on, the condition is considered true.

Line 7 performs a DOU (Do Until) operation. The expression used as the conditioning expression is simply *INLR. This is a valid condition, and evaluates to either a true or false condition. Because an indicator is either off or on, when its condition is tested, it returns true when the indicator is on and false when the indicator is off. To reverse this conditioning, specify the NOT operator in front of the indicator or simply evaluate the indicator to be equal to *OFF, as in DOU *INLR = *OFF.

Expressions in Declarative Statements

Built-in functions can be used in any expression. On the definition specification, basic expressions may be used as arguments for the various keywords. Expressions also are useful in establishing field referencing. When the properties of one item change, other items that depend on those properties also change. This is not the only use for expressions on the definition specification, but it is the most useful. Other uses include setting the initial value of a field, specifying the location of a data structure subfield, or calculating a mathematical formula.

Only expressions that can be analyzed at the time the source code is compiled may be specified. Hence, only literals, predefined values, and certain built-in functions are supported. Specifically, the value (content) of fields, arrays, and data structures cannot be used in an expression on the definition specification. Figure 3.3 illustrates several valid expressions as used on the definition specification function/keyword area.

start figure

 .....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++++++++++++++++++ 0001 D Amt_Len         S              5P 0 INZ(%size(AmountDue)) 0002 D Dft_Comp        C                   Const('Skyline Pigeon Productions') 0003 D Company         S                   LIKE(CORP_NAME) INZ(DFT_COMP) 0004 D Radius          C                   Const(16) 0005 D PI              C                   Const(3.1415926) 0006 D CubeRoot        S                   LIKE(AMT_LEN) 0007 D NewName         S             +4A   LIKE(CORP_NAME) 

end figure

Figure 3.3: Expressions on the definition specification.

Expressions in Parameters and Return Values

The CALLP and RETURN operations support expressions in the extended factor 2. The CALLP operation is used to evoke either a subprocedure or a separate program. The RETURN operation is used to specify the return value from a subprocedure to its caller. An expression can be specified for a parameter of a subprocedure call when that parameter is defined as CONST. In other words, the CONST keyword must be specified for the parameter in order for the RPG IV syntax checker to accept an expression for the parameter.

Expressions in Free Format Calculations

The free format version of RPG Calculation specifications is essentially expressions. While free format RPG syntax is not exactly the same as traditional RPG, expressions are used identically to traditional RPG. Free format expression may be specified in positions 8 to 80 of the source statement line.

To start using free format expressions, the /FREE-FORM directive must be specified on a line by itself in positions 7 through 16 of the RPG statement. Expressions may be specified on the line following the /FREE-FORM statement itself. The end free format expressions, a /END-FREE must be specified on a line by itself in positions 7 to 15.

Each free format expression must appear in positions 8 through 80 of the source statement and must be terminated with a semicolon (;).

Most traditional RPG operation codes may be used with free format expressions, however the syntax for operations is slightly modified. In free format, the operation code is specified first, followed by Factor 1, Factor 2, and the Result field. Resulting indicators are not supported in free format expressions. If an operation code does not require Factor 1, Factor 2 or the Result field, then those operands are not specified. Figure 3.4 illustrates the use of several free format expressions.

start figure

 ....._/Free-Form+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++       /FREE-FORM 0001      if      A = B; // Check for Zero pricing 0002        if      Price > 0 and DaysOvrDue >= 30; 0003          if     (Price - Cost) / Price < 10 or Cost = 0; 0004            read     Customer; 0005             DOW    NOT %EOF(CustMast); 0006               TotalSales += CustSales; 0007               read     Customer; 0008             endDo; 0009          EndIf; 0010        EndIf; 0011      EndIf;       /END-FREE 

end figure

Figure 3.4: Expressions in free format RPG.

Note that the conditional statement on line 3 is followed by a comment. Two forward slash characters begin a comment in free format expressions. Comments may be the last item on a source line or the only item on a source line. Everything following the two forward slash characters on the source line is ignored by the compiler.

Expressions as Parameters

Normally expressions may not be used as the value of a parameter passed to a procedure or program. However, by specifying that a parameter is passed by value or is read-only, expressions are fully supported.

In order to allow an expression to be used as the value of a parameter, one of the following parameter keywords must be used.

  • VALUE - The parameter is passed by value instead of the default, by reference.

  • CONST - The parameter is read-only, the called procedure may not change the value.

When the VALUE keyword is used the system makes a copy of the value and passes the copy to the called procedure. Since the original parameter value's storage is not accessed by the called procedure, the compiler allows additional items to be passed on the parameter. Specifically, literals, named constants, and expressions are allowed.

The following procedure does not use CONST or VALUE for its parameters, and therefore cannot accept expressions as parameter values.

 .....PProcName+++++++..B...................Functions+++++++++++++++++++++++ 0001 P Root            B                   Export .....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++++++++++++++++ 0002 D Root            PI            10I 0 0003 D nValue                         7P 0 0004 D nRoot                          5I 0 0005 D nRtnValue       S             10I 0 .....CSRn01..............OpCode(ex)Extended-factor2++++++++++++++++++++++++ 0006 C                   Eval      nRtnValue = %int(nValue ** (1/nRoot)) 0007 C                   return    nRtnValue 0008 P Root            E 

In order to permit expressions, either CONST or VALUE must be specified for the nValue and nRoot parameters. Neither parameter is modified by the procedure so both are candidates for these keywords.

Since the procedure does not modify the input parameters, the CONST keyword may be the better choice. The VALUE keyword would allow the parameter fields in the procedure to be modified within the procedure, but the modified values would not be passed back to the caller. The CONST keyword actually prohibits modification of the input parameters. Since the parameters are not modified, CONST is the correct choice. The following procedure has been modified to include the CONST keywords for its parameters.

 .....PProcName+++++++..B...................Functions+++++++++++++++++++++++ 0001 P Root            B                   Export .....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++++++++++++++++ 0002 D Root            PI            10I 0 0003 D nValue                         7P 0 CONST 0004 D nRoot                          5I 0 CONST 0005 D nRtnValue       S             10I 0 .....CSRn01..............OpCode(ex)Extended-factor2++++++++++++++++++++++++ 0006 C                   Eval      nRtnValue = %int(nValue ** (1/nRoot)) 0007 C                   return    nRtnValue 0008 P Root            E 

The ROOT procedure may now be called with any type of numeric data specified for its parameters, including expressions.

 .....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++++++++++++++++ 0001 D Root            PR            10I 0 0002 D Value                          7P 0 Const 0003 D Root                           5I 0 Const 0004 D Var1            S              5I 0 Inz(3741) 0005 D nRoot           S              5I 0 .....CSRn01..............OpCode(ex)Extended-factor2++++++++++++++ 0006 C                   Eval      nRoot = Root(Var1 * 2 : 3) 

An expression is specified on the first parameter of the ROOT procedure (line 6). The field VAR1 is multiplied by 2. The product of that expression is generated and is passed to the procedure. The literal 3 is specified on the second parameter. Then the procedure is called and the cubed root of 7482 is returned and assigned to NROOT variable.

Whether the CONST keyword is used or the VALUE keyword is used, the capability to specify expressions as parameters for procedures is allowed with either of these two keywords.




The Modern RPG IV Language
The Modern RPG IV Language
ISBN: 1583470646
EAN: 2147483647
Year: 2003
Pages: 156
Authors: Robert Cozzi

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net