ILE RPG for AS/400® Reference

ILE RPG for AS/400® Reference
AS/400e
ÉÂÔ
ILE RPG for AS/400
Reference
Version 4
SC09-2508-02
AS/400e
ÉÂÔ
ILE RPG for AS/400
Reference
Version 4
SC09-2508-02
Note!
Before using this information and the product it supports, be sure to read the general information under “Notices” on page xxi.
Third Edition (May 1999)
This edition applies to Version 4, Release 4, Modification 0, of IBM Application System/400 Integrated Language Environment RPG
for AS/400 (Program 5769-RG1) and to all subsequent releases and modifications until otherwise indicated in new editions. This
edition applies only to reduced instruction set computer (RISC) systems.
This edition replaces SC09-2508-01.
Order publications through your IBM representative or the IBM branch office serving your locality. Publications are not stocked at the
address given below.
IBM welcomes your comments. You can send your comments to:
IBM Canada Ltd. Laboratory
Information Development
2G/KB7/1150/TOR
1150 Eglinton Avenue East
North York, Ontario, Canada M3C 1H7
You can also send your comments by facsimile (attention: RCF Coordinator), or you can send your comments electronically to IBM.
See “How to Send Your Comments” for a description of the methods.
When you send information to IBM, you grant IBM a nonexclusive right to use or distribute the information in any way it believes
appropriate without incurring any obligation to you.
 Copyright International Business Machines Corporation 1994, 1999. All rights reserved.
Note to U.S. Government Users — Documentation related to restricted rights — Use, duplication or disclosure is subject to
restrictions set forth in GSA ADP Schedule Contract with IBM Corp.
Contents
Notices . . . . . . . . . . . . . . .
Programming Interface Information
Trademarks and Service Marks
.
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
About This Reference . . . . . . . . . .
Who Should Use This Reference
. . . .
Prerequisite and Related Information . .
How to Send Your Comments . . . . . .
What's New This Release? . . . . . . . .
Changes to this Reference Since V4R2
|
|
RPG IV Concepts
xxi
xxii
xxii
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
xxiii
xxiii
xxiii
xxiv
xxiv
xxix
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 1. Symbolic Names and Reserved Words
Symbolic Names . . . . . . . . . . . . . . . . . . . . . .
Array Names . . . . . . . . . . . . . . . . . . . . . . .
Conditional Compile Names . . . . . . . . . . . . . .
Data Structure Names . . . . . . . . . . . . . . . . .
EXCEPT Names . . . . . . . . . . . . . . . . . . . . .
Field Names . . . . . . . . . . . . . . . . . . . . . . .
KLIST Names . . . . . . . . . . . . . . . . . . . . . .
Labels . . . . . . . . . . . . . . . . . . . . . . . . . . .
Named Constants . . . . . . . . . . . . . . . . . . . .
PLIST Names . . . . . . . . . . . . . . . . . . . . . .
Prototype Names . . . . . . . . . . . . . . . . . . . .
Record Names . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
Subroutine Names
Table Names . . . . . . . . . . . . . . . . . . . . . . .
RPG IV Words with Special Functions/Reserved Words
User Date Special Words . . . . . . . . . . . . . . . . .
Rules for User Date . . . . . . . . . . . . . . . . . . .
PAGE, PAGE1-PAGE7 . . . . . . . . . . . . . . . . . .
Rules for PAGE, PAGE1-PAGE7 . . . . . . . . . . .
Chapter 2. Compiler Directives . . . . . . . . . .
/TITLE (Positions 7-12) . . . . . . . . . . . . . . . .
/EJECT (Positions 7-12) . . . . . . . . . . . . . . . .
/SPACE (Positions 7-12)
. . . . . . . . . . . . . . .
/COPY (Positions 7-11) . . . . . . . . . . . . . . . .
Results of the /COPY during Compile . . . . . .
Nested /COPY . . . . . . . . . . . . . . . . . . . .
Conditional Compilation Directives . . . . . . . . . .
Defining Conditions . . . . . . . . . . . . . . . . .
/DEFINE (Positions 7-13) . . . . . . . . . . . .
/UNDEFINE (Positions 7-15) . . . . . . . . . .
Condition Expressions . . . . . . . . . . . . . . .
Testing Conditions
. . . . . . . . . . . . . . . . .
/IF Condition-Expression (Positions 7-9) . . .
/ELSEIF Condition-Expression (Positions 7-13)
 Copyright IBM Corp. 1994, 1999
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
1
3
3
4
4
4
4
4
4
5
5
5
5
5
5
5
5
7
7
8
9
11
11
11
12
12
13
13
14
14
14
14
15
15
15
15
iii
/ELSE (Positions 7-11)
. .
/ENDIF (Positions 7-12) . .
Rules for Testing Conditions
The /EOF Directive . . . . . .
/EOF (Positions 7-10) . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 3. Program Cycle . . . . . . . . . .
General RPG IV Program Cycle . . . . . . . .
Detailed RPG IV Program Cycle . . . . . . . .
Detailed RPG IV Object Program Cycle . .
Initialization Subroutine . . . . . . . . . . . .
Match Fields Routine . . . . . . . . . . .
Overflow Routine . . . . . . . . . . . . . .
Lookahead Routine . . . . . . . . . . . .
Ending a Program without a Primary File .
Program Control of File Processing . . . . .
RPG IV Exception/Error Handling Routine
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
Chapter 4. RPG IV Indicators . . . . . . . . . . . .
Indicators Defined on RPG IV Specifications . . . . .
Overflow Indicators . . . . . . . . . . . . . . . . . .
Record Identifying Indicators . . . . . . . . . . . . .
Rules for Assigning Record Identifying Indicators
Control Level Indicators (L1-L9) . . . . . . . . . . .
Rules for Control Level Indicators . . . . . . . .
Split Control Field . . . . . . . . . . . . . . . . .
Field Indicators
. . . . . . . . . . . . . . . . . . . .
Rules for Assigning Field Indicators . . . . . . .
Resulting Indicators . . . . . . . . . . . . . . . . . .
Rules for Assigning Resulting Indicators . . . .
Indicators Not Defined on the RPG IV Specifications
External Indicators
. . . . . . . . . . . . . . . . . .
Internal Indicators . . . . . . . . . . . . . . . . . . .
First Page Indicator (1P) . . . . . . . . . . . . .
Last Record Indicator (LR) . . . . . . . . . . . .
Matching Record Indicator (MR) . . . . . . . . .
Return Indicator (RT) . . . . . . . . . . . . . . . . .
Using Indicators
. . . . . . . . . . . . . . . . . . . . .
File Conditioning . . . . . . . . . . . . . . . . . . . .
Rules for File Conditioning . . . . . . . . . . . .
Field Record Relation Indicators
. . . . . . . . . .
Assigning Field Record Relation Indicators . . .
Function Key Indicators
. . . . . . . . . . . . . . .
Halt Indicators (H1-H9) . . . . . . . . . . . . . . . .
Indicators Conditioning Calculations . . . . . . . .
Positions 7 and 8 . . . . . . . . . . . . . . . . . .
Positions 9-11
. . . . . . . . . . . . . . . . . . .
Indicators Used in Expressions . . . . . . . . . . .
Indicators Conditioning Output . . . . . . . . . . . .
Indicators Referred to As Data . . . . . . . . . . . . .
*IN . . . . . . . . . . . . . . . . . . . . . . . . . . . .
*INxx . . . . . . . . . . . . . . . . . . . . . . . . . .
Additional Rules . . . . . . . . . . . . . . . . . . . .
Summary of Indicators . . . . . . . . . . . . . . . . . .
iv
ILE RPG for AS/400 Reference
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
16
16
16
16
16
19
19
20
23
26
27
28
29
29
29
32
33
33
34
34
35
36
37
41
43
43
44
45
45
46
46
46
47
47
47
48
48
48
49
49
51
52
52
52
53
56
56
59
59
60
60
61
Chapter 5. File and Program Exception/Errors
File Exception/Errors . . . . . . . . . . . . . . . . .
File Information Data Structure . . . . . . . . .
File Feedback Information
. . . . . . . . . .
Open Feedback Information . . . . . . . . .
Input/Output Feedback Information . . . . .
Device Specific Feedback Information
. . .
Get Attributes Feedback Information
. . . .
Blocking Considerations . . . . . . . . . . . .
File Status Codes . . . . . . . . . . . . . . .
File Exception/Error Subroutine (INFSR) . . . .
Program Exception/Errors . . . . . . . . . . . . . .
Program Status Data Structure . . . . . . . . .
Program Status Codes
. . . . . . . . . . . .
PSDS Example . . . . . . . . . . . . . . . . .
Program Exception/Error Subroutine . . . . . .
Chapter 6. Subprocedures .
Subprocedure Definition . . . .
Procedure Interface Definition
Return Values . . . . . . . .
Scope of Definitions . . . . .
Subprocedure Calculations .
NOMAIN Module . . . . . . . .
Subprocedures and Subroutines
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 7. General File Considerations .
Primary/Secondary Multi-file Processing
. .
Multi-file Processing with No Match Fields
Multi-file Processing with Match Fields . .
Assigning Match Field Values (M1-M9)
Processing Matching Records . . . . .
File Translation . . . . . . . . . . . . . . . . .
Specifying File Translation . . . . . . . . .
Translating One File or All Files . . . . . .
Translating More Than One File
. . . . .
Specifying the Files . . . . . . . . . . .
Specifying the Table . . . . . . . . . . .
Definitions
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 8. Defining Data and Prototypes . .
General Considerations . . . . . . . . . . . . . .
Scope of Definitions . . . . . . . . . . . . . . .
Storage of Definitions . . . . . . . . . . . . . .
Standalone Fields
. . . . . . . . . . . . . . . . .
Variable Initialization . . . . . . . . . . . . . .
Constants . . . . . . . . . . . . . . . . . . . . . .
Literals . . . . . . . . . . . . . . . . . . . . . .
Example of Defining Literals . . . . . . . .
Example of Using Literals with Zero Length
Named Constants . . . . . . . . . . . . . . . .
Figurative Constants . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
Contents
65
65
65
66
69
70
72
74
77
77
80
82
82
86
88
89
91
91
92
93
93
94
97
97
99
99
99
99
100
104
107
108
108
109
109
110
111
113
113
114
115
116
116
116
117
120
120
121
122
v
Rules for Figurative Constants .
Data Structures . . . . . . . . . . . . .
Defining Data Structure Subfields .
Specifying Subfield Length . . .
Aligning Data Structure Subfields
Special Data Structures
. . . . . .
Data Area Data Structure . . . .
File Information Data Structure .
Program-Status Data Structure .
Indicator Data Structure . . . . .
Data Structure Examples . . . . . .
Prototypes and Parameters . . . . . .
Prototypes . . . . . . . . . . . . . .
Prototyped Parameters . . . . . . .
Procedure Interface . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
Chapter 9. Using Arrays and Tables . . . . . . . . . . . . . .
Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Array Name and Index . . . . . . . . . . . . . . . . . . . . . .
The Essential Array Specifications . . . . . . . . . . . . . . .
Coding a Run-Time Array . . . . . . . . . . . . . . . . . . . .
Loading a Run-Time Array . . . . . . . . . . . . . . . . . . . .
Loading a Run-Time Array in One Source Record
. . . .
Loading a Run-Time Array Using Multiple Source Records
Sequencing Run-Time Arrays
. . . . . . . . . . . . . . . .
Coding a Compile-Time Array . . . . . . . . . . . . . . . . . .
Loading a Compile-Time Array . . . . . . . . . . . . . . . . .
Rules for Array Source Records . . . . . . . . . . . . . . .
Coding a Prerun-Time Array . . . . . . . . . . . . . . . . . . .
Example of Coding Arrays . . . . . . . . . . . . . . . . . . . .
Loading a Prerun-Time Array . . . . . . . . . . . . . . . . . .
Sequence Checking for Character Arrays . . . . . . . . . . .
Initializing Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
Run-Time Arrays
Compile-Time and Prerun-Time Arrays . . . . . . . . . . . . .
Defining Related Arrays . . . . . . . . . . . . . . . . . . . . . . .
Searching Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . .
Searching an Array Without an Index
. . . . . . . . . . . . .
Searching an Array with an Index . . . . . . . . . . . . . . . .
Using Arrays
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Specifying an Array in Calculations . . . . . . . . . . . . . . .
Sorting Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sorting using part of the array as a key . . . . . . . . . . . .
Array Output
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Editing Entire Arrays . . . . . . . . . . . . . . . . . . . . . . .
Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
LOOKUP with One Table
. . . . . . . . . . . . . . . . . . . .
LOOKUP with Two Tables . . . . . . . . . . . . . . . . . . . .
Specifying the Table Element Found in a LOOKUP Operation
Chapter 10. Data Types and Data Formats
Internal and External Formats
. . . . . . . .
Internal Format
. . . . . . . . . . . . . . .
External Format . . . . . . . . . . . . . . .
vi
ILE RPG for AS/400 Reference
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
123
124
125
125
125
126
127
127
127
127
128
138
138
139
141
143
143
144
144
144
145
145
146
146
146
146
147
148
148
149
149
150
150
150
151
152
152
153
154
154
155
155
156
156
157
157
157
158
159
159
160
160
|
|
|
|
|
|
|
|
Specifying an External Format for a Numeric Field . . . . . . . . . . . .
Specifying an External Format for a Character, Graphic, or UCS-2 Field
Specifying an External Format for a Date-Time Field . . . . . . . . . . .
Character Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Character Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Indicator Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Graphic Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
UCS-2 Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Variable-Length Character, Graphic and UCS-2 Formats . . . . . . . . . .
Rules for Variable-Length Character, Graphic, and UCS-2 Formats . .
Using Variable-Length Fields . . . . . . . . . . . . . . . . . . . . . . . . .
CVTOPT(*VARCHAR) and CVTOPT(*VARGRAPHIC) . . . . . . . . . .
Conversion between Character, Graphic and UCS-2 Data
. . . . . . . . .
CCSIDs of Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Alternate Collating Sequence . . . . . . . . . . . . . . . . . . . . . . . . . .
Changing the Collating Sequence . . . . . . . . . . . . . . . . . . . . . .
Using an External Collating Sequence . . . . . . . . . . . . . . . . . . .
Specifying an Alternate Collating Sequence in Your Source . . . . . . .
Formatting the Alternate Collating Sequence Records . . . . . . . . . .
Numeric Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Binary Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Processing of a Program-Described Binary Input Field . . . . . . . . . .
. . . . . . . .
Processing of an Externally Described Binary Input Field
Float Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
External Display Representation of a Floating-Point Field . . . . . . . .
Integer Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Packed-Decimal Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Determining the Digit Length of a Packed-Decimal Field . . . . . . . . .
Unsigned Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Zoned-Decimal Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Considerations for Using Numeric Formats . . . . . . . . . . . . . . . . . .
Guidelines for Choosing the Numeric Format for a Field . . . . . . . . .
Representation of Numeric Formats . . . . . . . . . . . . . . . . . . . . . .
Date Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Separators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Time Data Type
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Separators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
*JOBRUN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Timestamp Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Separators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Basing Pointer Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Setting a Basing Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Procedure Pointer Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Database Null Value Support . . . . . . . . . . . . . . . . . . . . . . . . . . . .
User Controlled Support for Null-Capable Fields and Key Fields . . . . . .
Input of Null-Capable Fields . . . . . . . . . . . . . . . . . . . . . . . . .
Output of Null-Capable Fields . . . . . . . . . . . . . . . . . . . . . . . .
Keyed Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Input-Only Support for Null-Capable Fields . . . . . . . . . . . . . . . . . .
Contents
160
161
161
162
162
163
163
164
165
166
168
170
173
173
174
174
174
175
175
175
176
176
177
177
177
178
179
180
180
181
181
182
183
183
185
188
188
188
189
189
189
190
190
190
190
192
192
196
198
198
199
199
201
203
vii
ALWNULL(*NO) . . . . . . . . . . . . . . . . . .
Error Handling for Database Data Mapping Errors
Chapter 11. Editing Numeric Fields
. . . .
Edit Codes . . . . . . . . . . . . . . . . . . . . .
Simple Edit Codes
. . . . . . . . . . . . . .
Combination Edit Codes . . . . . . . . . . .
User-Defined Edit Codes . . . . . . . . . . .
Editing Considerations . . . . . . . . . . . .
Summary of Edit Codes . . . . . . . . . . .
Edit Words . . . . . . . . . . . . . . . . . . . . .
How to Code an Edit Word
. . . . . . . . .
Parts of an Edit Word . . . . . . . . . . . . .
Forming the Body of an Edit Word . . . .
Forming the Status of an Edit Word . . .
Formatting the Expansion of an Edit Word
Summary of Coding Rules for Edit Words .
Editing Externally Described Files . . . . . . .
Specifications
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 12. About Specifications . . . . . . . . . . .
RPG IV Specification Types . . . . . . . . . . . . . . . .
Main Source Section Specifications . . . . . . . . . .
Subprocedure Specifications . . . . . . . . . . . . . .
Program Data . . . . . . . . . . . . . . . . . . . . . .
Common Entries . . . . . . . . . . . . . . . . . . . . . .
Syntax of Keywords . . . . . . . . . . . . . . . . . . .
Continuation Rules . . . . . . . . . . . . . . . . . . .
Control Specification Keyword Field . . . . . . . .
File Description Specification Keyword Field . . .
Definition Specification Keyword Field . . . . . . .
Calculation Specification Extended Factor-2 . . .
. .
Output Specification Constant/Editword Field
Definition and Procedure Specification Name Field
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . .
Chapter 13. Control Specifications . . . . . . . . . . . . . . . .
Using a Data Area as a Control Specification
. . . . . . . . . . .
Control-Specification Statement
. . . . . . . . . . . . . . . . . . .
Position 6 (Form Type) . . . . . . . . . . . . . . . . . . . . . . .
Positions 7-80 (Keywords) . . . . . . . . . . . . . . . . . . . . .
Control-Specification Keywords . . . . . . . . . . . . . . . . . . . .
ACTGRP(*NEW | *CALLER | 'activation-group-name') . . . . .
ALTSEQ{(*NONE | *SRC | *EXT)} . . . . . . . . . . . . . . . .
ALWNULL(*NO | *INPUTONLY | *USRCTL)
. . . . . . . . . .
AUT(*LIBRCRTAUT | *ALL | *CHANGE | *USE | *EXCLUDE |
'authorization-list-name')
. . . . . . . . . . . . . . . . . . . . .
BNDDIR('binding-directory-name' {:'binding-directory-name'...})
CCSID(*GRAPH : parameter | *UCS2 : number) . . . . . . . .
COPYNEST(number) . . . . . . . . . . . . . . . . . . . . . . . .
COPYRIGHT('copyright string') . . . . . . . . . . . . . . . . . .
CURSYM('sym') . . . . . . . . . . . . . . . . . . . . . . . . . . .
|
viii
ILE RPG for AS/400 Reference
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
203
203
205
206
206
206
208
208
209
212
213
213
214
217
217
218
218
219
221
221
222
223
223
224
224
225
227
228
228
228
229
229
231
231
231
232
232
232
233
233
234
234
235
235
236
236
237
|
|
|
CVTOPT(*{NO}DATETIME *{NO}GRAPHIC *{NO}VARCHAR
*{NO}VARGRAPHIC) . . . . . . . . . . . . . . . . . . . . . . . . . .
DATEDIT(fmt{separator}) . . . . . . . . . . . . . . . . . . . . . . . . .
DATFMT(fmt{separator}) . . . . . . . . . . . . . . . . . . . . . . . . .
DEBUG{(*NO | *YES)} . . . . . . . . . . . . . . . . . . . . . . . . . .
DECEDIT(*JOBRUN | 'value') . . . . . . . . . . . . . . . . . . . . . .
DFTACTGRP(*YES | *NO) . . . . . . . . . . . . . . . . . . . . . . . .
DFTNAME(rpg_name) . . . . . . . . . . . . . . . . . . . . . . . . . .
ENBPFRCOL(*PEP | *ENTRYEXIT | *FULL) . . . . . . . . . . . . .
EXPROPTS(*MAXDIGITS | *RESDECPOS) . . . . . . . . . . . . . .
EXTBININT{(*NO | *YES)} . . . . . . . . . . . . . . . . . . . . . . . .
FIXNBR(*{NO}ZONED *{NO}INPUTPACKED)
. . . . . . . . . . . .
FLTDIV{(*NO | *YES)} . . . . . . . . . . . . . . . . . . . . . . . . . .
FORMSALIGN{(*NO | *YES)} . . . . . . . . . . . . . . . . . . . . . .
FTRANS{(*NONE | *SRC)} . . . . . . . . . . . . . . . . . . . . . . . .
GENLVL(number) . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
INDENT(*NONE | 'character-value')
. . . . . . . . . . . . . . . . . .
INTPREC(10 | 20) . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
LANGID(*JOBRUN | *JOB | 'language-identifier') . . . . . . . . . . .
NOMAIN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
OPENOPT (*NOINZOFL | *INZOFL) . . . . . . . . . . . . . . . . . .
OPTIMIZE(*NONE | *BASIC | *FULL) . . . . . . . . . . . . . . . . .
OPTION(*{NO}XREF *{NO}GEN *{NO}SECLVL *{NO}SHOWCPY
*{NO}EXPDDS *{NO}EXT *{NO}SHOWSKP) *{NO}SRCSTMT)
*{NO}DEBUGIO) . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PRFDTA(*NOCOL | *COL) . . . . . . . . . . . . . . . . . . . . . . . .
SRTSEQ(*HEX | *JOB | *JOBRUN | *LANGIDUNQ | *LANGIDSHR |
'sort-table-name')
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
TEXT(*SRCMBRTXT | *BLANK | 'description') . . . . . . . . . . . .
THREAD(*SERIALIZE) . . . . . . . . . . . . . . . . . . . . . . . . . .
TIMFMT(fmt{separator}) . . . . . . . . . . . . . . . . . . . . . . . . .
TRUNCNBR(*YES | *NO) . . . . . . . . . . . . . . . . . . . . . . . .
USRPRF(*USER | *OWNER) . . . . . . . . . . . . . . . . . . . . . .
Chapter 14. File Description Specifications
File Description Specification Statement
. . .
File-Description Keyword Continuation Line
Position 6 (Form Type) . . . . . . . . . . . .
Positions 7-16 (File Name) . . . . . . . . . .
Program Described File . . . . . . . . . .
Externally Described File . . . . . . . . .
Position 17 (File Type) . . . . . . . . . . . .
Input Files . . . . . . . . . . . . . . . . . .
Output Files . . . . . . . . . . . . . . . . .
Update Files
. . . . . . . . . . . . . . . .
Combined Files . . . . . . . . . . . . . . .
Position 18 (File Designation) . . . . . . . .
Primary File . . . . . . . . . . . . . . . . .
Secondary File . . . . . . . . . . . . . . .
Record Address File (RAF) . . . . . . . .
Array or Table File . . . . . . . . . . . . .
Full Procedural File . . . . . . . . . . . .
Position 19 (End of File) . . . . . . . . . . .
Position 20 (File Addition) . . . . . . . . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
Contents
237
238
238
238
238
239
240
240
240
240
241
241
242
242
242
242
243
243
243
244
244
244
245
246
246
246
247
247
248
249
249
249
250
250
250
250
251
251
251
251
251
251
252
252
252
252
252
253
253
ix
Position 21 (Sequence) . . . . . . . . . . . . . . . .
Position 22 (File Format) . . . . . . . . . . . . . . .
Positions 23-27 (Record Length) . . . . . . . . . .
Position 28 (Limits Processing) . . . . . . . . . . .
Positions 29-33 (Length of Key or Record Address)
Position 34 (Record Address Type) . . . . . . . . .
Blank=Non-keyed Processing
. . . . . . . . . .
A=Character Keys . . . . . . . . . . . . . . . . .
P=Packed Keys
. . . . . . . . . . . . . . . . . .
G=Graphic Keys . . . . . . . . . . . . . . . . . .
K=Key . . . . . . . . . . . . . . . . . . . . . . . .
D=Date Keys . . . . . . . . . . . . . . . . . . . .
T=Time Keys . . . . . . . . . . . . . . . . . . . .
Z=Timestamp Keys
. . . . . . . . . . . . . . . .
F=Float Keys . . . . . . . . . . . . . . . . . . . .
Position 35 (File Organization)
. . . . . . . . . . .
Blank=Non-keyed Program-Described File . . .
I=Indexed File
. . . . . . . . . . . . . . . . . . .
T=Record Address File . . . . . . . . . . . . . .
Positions 36-42 (Device) . . . . . . . . . . . . . . .
Position 43 (Reserved) . . . . . . . . . . . . . . . .
Positions 44-80 (Keywords) . . . . . . . . . . . . .
File-Description Keywords . . . . . . . . . . . . . . . .
BLOCK(*YES |*NO) . . . . . . . . . . . . . . . . . .
COMMIT{(rpg_name)}
. . . . . . . . . . . . . . . .
DATFMT(format{separator}) . . . . . . . . . . . . .
DEVID(fieldname) . . . . . . . . . . . . . . . . . . .
EXTIND(*INUx) . . . . . . . . . . . . . . . . . . . .
FORMLEN(number) . . . . . . . . . . . . . . . . . .
FORMOFL(number) . . . . . . . . . . . . . . . . . .
IGNORE(recformat{:recformat...}) . . . . . . . . . .
INCLUDE(recformat{:recformat...}) . . . . . . . . .
INDDS(data_structure_name) . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
INFDS(DSname)
INFSR(SUBRname) . . . . . . . . . . . . . . . . . .
KEYLOC(number) . . . . . . . . . . . . . . . . . . .
MAXDEV(*ONLY | *FILE)
. . . . . . . . . . . . . .
OFLIND(*INxx) . . . . . . . . . . . . . . . . . . . . .
PASS(*NOIND) . . . . . . . . . . . . . . . . . . . .
PGMNAME(program_name) . . . . . . . . . . . . .
PLIST(Plist_name)
. . . . . . . . . . . . . . . . . .
PREFIX(prefix_string{:nbr_of_char_replaced})
. .
PRTCTL(data_struct{:*COMPAT})
. . . . . . . . .
Extended Length PRTCTL Data Structure . . .
*COMPAT PRTCTL Data Structure . . . . . . .
RAFDATA(filename)
. . . . . . . . . . . . . . . . .
RECNO(fieldname) . . . . . . . . . . . . . . . . . .
RENAME(Ext_format:Int_format) . . . . . . . . . .
SAVEDS(DSname) . . . . . . . . . . . . . . . . . .
SAVEIND(number) . . . . . . . . . . . . . . . . . .
SFILE(recformat:rrnfield) . . . . . . . . . . . . . . .
SLN(number) . . . . . . . . . . . . . . . . . . . . . .
TIMFMT(format{separator})
. . . . . . . . . . . . .
USROPN . . . . . . . . . . . . . . . . . . . . . . . .
x
ILE RPG for AS/400 Reference
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
254
255
255
255
256
256
257
257
258
258
258
258
258
259
259
259
259
259
259
260
260
260
260
261
262
262
262
263
263
264
264
264
264
265
265
265
265
266
266
266
267
267
267
268
268
268
269
269
269
269
270
270
270
271
File Types and Processing Methods
|
. . . . . . . . . . . . . . . . . . . . . . . .
Chapter 15. Definition Specifications
. . . . . . . . . . . . . .
Definition Specification Statement . . . . . . . . . . . . . . . . . .
Definition Specification Keyword Continuation Line . . . . . . .
Definition Specification Continued Name Line . . . . . . . . . .
Position 6 (Form Type) . . . . . . . . . . . . . . . . . . . . . . .
Positions 7-21 (Name) . . . . . . . . . . . . . . . . . . . . . . .
Position 22 (External Description) . . . . . . . . . . . . . . . . .
Position 23 (Type of Data Structure) . . . . . . . . . . . . . . .
Positions 24-25 (Definition Type) . . . . . . . . . . . . . . . . .
Positions 26-32 (From Position) . . . . . . . . . . . . . . . . . .
Positions 33-39 (To Position / Length) . . . . . . . . . . . . . .
Position 40 (Internal Data Type)
. . . . . . . . . . . . . . . . .
Positions 41-42 (Decimal Positions)
. . . . . . . . . . . . . . .
Position 43 (Reserved) . . . . . . . . . . . . . . . . . . . . . . .
Positions 44-80 (Keywords) . . . . . . . . . . . . . . . . . . . .
Definition-Specification Keywords
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ALIGN
ALT(array_name) . . . . . . . . . . . . . . . . . . . . . . . . . .
ALTSEQ(*NONE) . . . . . . . . . . . . . . . . . . . . . . . . . .
ASCEND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
BASED(basing_pointer_name)
. . . . . . . . . . . . . . . . . .
CCSID(number | *DFT) . . . . . . . . . . . . . . . . . . . . . . .
CONST{(constant)} . . . . . . . . . . . . . . . . . . . . . . . . .
CTDATA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
DATFMT(format{separator}) . . . . . . . . . . . . . . . . . . . .
DESCEND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
DIM(numeric_constant) . . . . . . . . . . . . . . . . . . . . . . .
DTAARA{(data_area_name)} . . . . . . . . . . . . . . . . . . .
EXPORT{(external_name)} . . . . . . . . . . . . . . . . . . . . .
EXTFLD(field_name) . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
EXTFMT(code)
. . . . . . . . . . . . . .
EXTNAME(file_name{:format_name})
EXTPGM(name) . . . . . . . . . . . . . . . . . . . . . . . . . . .
EXTPROC(name) . . . . . . . . . . . . . . . . . . . . . . . . . .
FROMFILE(file_name) . . . . . . . . . . . . . . . . . . . . . . .
IMPORT{(external_name)} . . . . . . . . . . . . . . . . . . . . .
INZ{(initial value)} . . . . . . . . . . . . . . . . . . . . . . . . . .
LIKE(RPG_name) . . . . . . . . . . . . . . . . . . . . . . . . . .
NOOPT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
OCCURS(numeric_constant)
. . . . . . . . . . . . . . . . . . .
OPDESC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
OPTIONS(*NOPASS *OMIT *VARSIZE *STRING *RIGHTADJ)
OVERLAY(name{:pos | *NEXT})
. . . . . . . . . . . . . . . . .
PACKEVEN . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PERRCD(numeric_constant) . . . . . . . . . . . . . . . . . . . .
PREFIX(prefix_string{:nbr_of_char_replaced})
. . . . . . . . .
PROCPTR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
STATIC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
TIMFMT(format{separator})
. . . . . . . . . . . . . . . . . . . .
TOFILE(file_name) . . . . . . . . . . . . . . . . . . . . . . . . .
VALUE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
VARYING . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
Contents
271
273
273
274
274
274
275
275
276
276
277
277
278
279
279
279
279
280
281
281
281
282
282
283
283
284
284
284
285
285
286
286
287
288
288
289
289
290
291
292
293
294
294
300
302
302
303
303
303
304
304
304
304
xi
Summary According to Definition Specification Type
Named Constant Keyword
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
Chapter 16. Input Specifications . . . . . . . . . .
Input Specification Statement . . . . . . . . . . . . . .
Program Described . . . . . . . . . . . . . . . . . .
Externally Described . . . . . . . . . . . . . . . . .
Program Described Files
. . . . . . . . . . . . . . . .
Position 6 (Form Type) . . . . . . . . . . . . . . . .
Record Identification Entries
. . . . . . . . . . . . . .
Positions 7-16 (File Name) . . . . . . . . . . . . . .
Positions 16-18 (Logical Relationship) . . . . . . .
Positions 17-18 (Sequence) . . . . . . . . . . . . .
Alphabetic Entries . . . . . . . . . . . . . . . . .
Numeric Entries
. . . . . . . . . . . . . . . . . .
Position 19 (Number) . . . . . . . . . . . . . . . . .
Position 20 (Option) . . . . . . . . . . . . . . . . . .
Positions 21-22 (Record Identifying Indicator, or **)
Indicators . . . . . . . . . . . . . . . . . . . . . .
Lookahead Fields
. . . . . . . . . . . . . . . . .
Positions 23-46 (Record Identification Codes) . . .
Positions 23-27, 31-35, and 39-43 (Position) . .
Positions 28, 36, and 44 (Not) . . . . . . . . . .
Positions 29, 37, and 45 (Code Part) . . . . . .
Positions 30, 38, and 46 (Character) . . . . . .
. . . . . . . . . . . . . . . . .
AND Relationship
OR Relationship . . . . . . . . . . . . . . . . . .
Field Description Entries . . . . . . . . . . . . . . . . .
Position 6 (Form Type) . . . . . . . . . . . . . . . .
Positions 7-30 (Reserved) . . . . . . . . . . . . . .
Positions 31-34 (Data Attributes) . . . . . . . . . .
Position 35 (Date/Time Separator) . . . . . . . . .
Position 36 (Data Format) . . . . . . . . . . . . . .
Positions 37-46 (Field Location) . . . . . . . . . . .
Positions 47-48 (Decimal Positions)
. . . . . . . .
Positions 49-62 (Field Name) . . . . . . . . . . . .
Positions 63-64 (Control Level) . . . . . . . . . . .
Positions 65-66 (Matching Fields) . . . . . . . . . .
Positions 67-68 (Field Record Relation) . . . . . .
Positions 69-74 (Field Indicators) . . . . . . . . . .
Externally Described Files . . . . . . . . . . . . . . . .
Position 6 (Form Type) . . . . . . . . . . . . . . . .
Record Identification Entries
. . . . . . . . . . . . . .
Positions 7-16 (Record Name)
. . . . . . . . . . .
Positions 17-20 (Reserved) . . . . . . . . . . . . .
Positions 21-22 (Record Identifying Indicator) . . .
Positions 23-80 (Reserved) . . . . . . . . . . . . .
Field Description Entries . . . . . . . . . . . . . . . . .
Positions 7-20 (Reserved) . . . . . . . . . . . . . .
Positions 21-30 (External Field Name) . . . . . . .
Positions 31-48 (Reserved) . . . . . . . . . . . . .
Positions 49-62 (Field Name) . . . . . . . . . . . .
Positions 63-64 (Control Level) . . . . . . . . . . .
Positions 65-66 (Matching Fields) . . . . . . . . . .
xii
ILE RPG for AS/400 Reference
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
305
307
309
309
309
310
310
310
310
310
311
311
311
311
312
312
312
312
313
313
314
314
314
315
315
316
316
316
316
316
316
317
317
318
318
319
319
320
320
321
321
321
321
322
322
322
322
322
322
322
322
323
323
Positions 67-68 (Reserved) . .
Positions 69-74 (Field Indicators)
Positions 75-80 (Reserved) . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 17. Calculation Specifications
. . . . . . . . . . . .
Calculation Specification Statement . . . . . . . . . . . . . . . .
Calculation Specification Extended Factor-2 Continuation Line
Position 6 (Form Type) . . . . . . . . . . . . . . . . . . . . . .
Positions 7-8 (Control Level) . . . . . . . . . . . . . . . . . . .
Control Level Indicators . . . . . . . . . . . . . . . . . . . .
Last Record Indicator . . . . . . . . . . . . . . . . . . . . .
Subroutine Identifier . . . . . . . . . . . . . . . . . . . . . .
AND/OR Lines Identifier . . . . . . . . . . . . . . . . . . . .
Positions 9-11 (Indicators) . . . . . . . . . . . . . . . . . . . .
Positions 12-25 (Factor 1) . . . . . . . . . . . . . . . . . . . .
Positions 26-35 (Operation and Extender) . . . . . . . . . . .
Operation Extender . . . . . . . . . . . . . . . . . . . . . .
Positions 36-49 (Factor 2) . . . . . . . . . . . . . . . . . . . .
Positions 50-63 (Result Field) . . . . . . . . . . . . . . . . . .
Positions 64-68 (Field Length) . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . .
Positions 69-70 (Decimal Positions)
Positions 71-76 (Resulting Indicators) . . . . . . . . . . . . .
Calculation Extended Factor 2 Specification Statement . . . . .
Positions 7-8 (Control Level) . . . . . . . . . . . . . . . . . . .
Positions 9-11 (Indicators) . . . . . . . . . . . . . . . . . . . .
Positions 12-25 (Factor 1) . . . . . . . . . . . . . . . . . . . .
Positions 26-35 (Operation and Extender) . . . . . . . . . . .
Operation Extender . . . . . . . . . . . . . . . . . . . . . .
Positions 36-80 (Extended Factor 2) . . . . . . . . . . . . . .
Chapter 18. Output Specifications . . . . . . .
Output Specification Statement . . . . . . . . . . .
Program Described . . . . . . . . . . . . . . . .
Externally Described . . . . . . . . . . . . . . .
Program Described Files
. . . . . . . . . . . . . .
Position 6 (Form Type) . . . . . . . . . . . . . .
Record Identification and Control Entries . . . . .
Positions 7-16 (File Name) . . . . . . . . . . . .
Positions 16-18 ( Logical Relationship) . . . . .
Position 17 (Type) . . . . . . . . . . . . . . . . .
Positions 18-20 (Record Addition/Deletion) . .
Position 18 (Fetch Overflow/Release) . . . . .
Fetch Overflow . . . . . . . . . . . . . . . . .
Release . . . . . . . . . . . . . . . . . . . . .
Positions 21-29 (Output Conditioning Indicators)
Positions 30-39 (EXCEPT Name) . . . . . . . .
Positions 40-51 (Space and Skip) . . . . . . . .
Positions 40-42 (Space Before) . . . . . . . . .
Positions 43-45 (Space After) . . . . . . . . . .
Positions 46-48 (Skip Before) . . . . . . . . . .
Positions 49-51 (Skip After) . . . . . . . . . . .
Field Description and Control Entries . . . . . . .
Positions 21-29 (Output Indicators) . . . . . . .
Positions 30-43 (Field Name) . . . . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
323
323
324
325
325
326
326
326
327
327
327
327
328
328
328
328
330
330
330
330
331
331
332
332
332
332
332
332
. . . . . . . . . . . . . . . .
335
335
335
336
336
336
336
336
337
337
337
338
338
338
339
340
341
341
341
341
342
342
342
342
Contents
xiii
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
Field Names, Blanks, Tables and Arrays . . . . . . . . . . . . . . .
PAGE, PAGE1-PAGE7 . . . . . . . . . . . . . . . . . . . . . . . . .
*PLACE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
User Date Reserved Words
. . . . . . . . . . . . . . . . . . . . . .
*IN, *INxx, *IN(xx) . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Position 44 (Edit Codes) . . . . . . . . . . . . . . . . . . . . . . . . . .
Position 45 (Blank After) . . . . . . . . . . . . . . . . . . . . . . . . . .
Positions 47-51 (End Position)
. . . . . . . . . . . . . . . . . . . . . .
Position 52 (Data Format) . . . . . . . . . . . . . . . . . . . . . . . . .
Positions 53-80 (Constant, Edit Word, Data Attributes, Format Name)
Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Edit Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Data Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Record Format Name . . . . . . . . . . . . . . . . . . . . . . . . . .
Externally Described Files . . . . . . . . . . . . . . . . . . . . . . . . . . .
Position 6 (Form Type) . . . . . . . . . . . . . . . . . . . . . . . . . . .
Record Identification and Control Entries . . . . . . . . . . . . . . . . . .
Positions 7-16 (Record Name)
. . . . . . . . . . . . . . . . . . . . . .
Positions 16-18 (Logical Relationship) . . . . . . . . . . . . . . . . . .
Position 17 (Type) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Position 18 (Release) . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Positions 18-20 (Record Addition)
. . . . . . . . . . . . . . . . . . . .
Positions 21-29 (Output Indicators) . . . . . . . . . . . . . . . . . . . .
Positions 30-39 (EXCEPT Name) . . . . . . . . . . . . . . . . . . . . .
Field Description and Control Entries . . . . . . . . . . . . . . . . . . . .
Positions 21-29 (Output Indicators) . . . . . . . . . . . . . . . . . . . .
Positions 30-43 (Field Name) . . . . . . . . . . . . . . . . . . . . . . .
Position 45 (Blank After) . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 19. Procedure Specifications . . . . . . .
Procedure Specification Statement . . . . . . . . . . .
Procedure Specification Keyword Continuation Line
Procedure Specification Continued Name Line . .
Position 6 (Form Type) . . . . . . . . . . . . . . . .
Positions 7-21 (Name) . . . . . . . . . . . . . . . .
Position 24 (Begin/End Procedure) . . . . . . . . .
Positions 44-80 (Keywords) . . . . . . . . . . . . .
Procedure-Specification Keywords . . . . . . . . . . .
EXPORT . . . . . . . . . . . . . . . . . . . . . . . .
Built-in Functions, Expressions, and Operation Codes
xiv
ILE RPG for AS/400 Reference
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
Chapter 20. Built-in Functions . . . . . . . . . . . . . . . . . . . .
Built-in Functions Alphabetically . . . . . . . . . . . . . . . . . . . .
%ABS (Absolute Value of Expression) . . . . . . . . . . . . . . .
%ADDR (Get Address of Variable) . . . . . . . . . . . . . . . . .
%CHAR (Convert to Character Data) . . . . . . . . . . . . . . . .
%DEC (Convert to Packed Decimal Format) . . . . . . . . . . .
%DECH (Convert to Packed Decimal Format with Half Adjust)
%DECPOS (Get Number of Decimal Positions) . . . . . . . . . .
%DIV (Return Integer Portion of Quotient) . . . . . . . . . . . . .
%EDITC (Edit Value Using an Editcode) . . . . . . . . . . . . . .
%EDITFLT (Convert to Float External Representation) . . . . .
|
. . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
342
343
343
343
343
343
344
344
345
347
347
347
347
348
348
348
348
348
348
348
349
349
349
349
349
349
349
350
351
351
352
352
352
352
353
353
353
353
355
357
362
362
363
365
366
366
367
368
369
372
|
|
|
|
%EDITW (Edit Value Using an Editword) . . . . . . . . . .
%ELEM (Get Number of Elements) . . . . . . . . . . . . . .
%EOF (Return End or Beginning of File Condition)
. . . .
%EQUAL (Return Exact Match Condition) . . . . . . . . . .
%ERROR (Return Error Condition) . . . . . . . . . . . . . .
%FLOAT (Convert to Floating Format) . . . . . . . . . . . .
%FOUND (Return Found Condition) . . . . . . . . . . . . .
%GRAPH (Convert to Graphic Value) . . . . . . . . . . . .
%INT (Convert to Integer Format)
. . . . . . . . . . . . . .
%INTH (Convert to Integer Format with Half Adjust) . .
%LEN (Get or Set Length) . . . . . . . . . . . . . . . . . . .
%LEN Used for its Value . . . . . . . . . . . . . . . . . .
%LEN Used to Set the Length of Variable-Length Fields
%NULLIND (Query or Set Null Indicator)
. . . . . . . . . .
%OPEN (Return File Open Condition) . . . . . . . . . . . .
%PADDR (Get Procedure Address)
. . . . . . . . . . . . .
%PARMS (Return Number of Parameters) . . . . . . . . .
%REM (Return Integer Remainder) . . . . . . . . . . . . . .
%REPLACE (Replace Character String) . . . . . . . . . . .
%SCAN (Scan for Characters)
. . . . . . . . . . . . . . . .
%SIZE (Get Size in Bytes) . . . . . . . . . . . . . . . . . . .
%STATUS (Return File or Program Status) . . . . . . . . .
%STR (Get or Store Null-Terminated String) . . . . . . . .
%STR Used to Get Null-Terminated String . . . . . . . .
%STR Used to Store Null-Terminated String . . . . . . .
. . . . . . . . . . . . . . . . . . .
%SUBST (Get Substring)
%SUBST Used for its Value . . . . . . . . . . . . . . . .
%SUBST Used as the Result of an Assignment . . . . .
%TRIM (Trim Blanks at Edges) . . . . . . . . . . . . . . . .
%TRIML (Trim Leading Blanks) . . . . . . . . . . . . . . . .
%TRIMR (Trim Trailing Blanks) . . . . . . . . . . . . . . . .
%UCS2 (Convert to UCS-2 Value) . . . . . . . . . . . . . .
%UNS (Convert to Unsigned Format) . . . . . . . . . . . .
%UNSH (Convert to Unsigned Format with Half Adjust)
%XFOOT (Sum Array Expression Elements) . . . . . . . .
Chapter 21. Expressions . . . . . . . . . . . . . . . . .
General Expression Rules . . . . . . . . . . . . . . . . . .
Expression Operands . . . . . . . . . . . . . . . . . . . .
Expression Operators . . . . . . . . . . . . . . . . . . . .
Operation Precedence . . . . . . . . . . . . . . . . . . . .
Data Types . . . . . . . . . . . . . . . . . . . . . . . . . .
Data Types Supported by Expression Operands . . .
Format of Numeric Intermediate Results . . . . . . . .
For the operators +, -, and *:
. . . . . . . . . . . .
For the / operator: . . . . . . . . . . . . . . . . . . .
For the ** operator:
. . . . . . . . . . . . . . . . . .
Precision Rules for Numeric Operations . . . . . . . . . .
Using the Default Precision Rules
. . . . . . . . . . .
Precision of Intermediate Results . . . . . . . . . . . .
Example of Default Precision Rules
. . . . . . . . . .
Using the "Result Decimal Position" Precision Rules .
Example of "Result Decimal Position" Precision Rules
Short Circuit Evaluation . . . . . . . . . . . . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
Contents
373
374
375
377
379
380
381
383
384
384
385
385
386
388
389
390
391
393
394
396
397
399
401
401
402
403
403
403
405
406
407
408
409
409
410
411
412
413
413
414
415
416
418
418
418
419
419
420
420
421
422
423
424
xv
Order of Evaluation
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 22. Operation Codes . . . . . . . . . . . . . . . . . .
Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . .
Ensuring Accuracy
. . . . . . . . . . . . . . . . . . . . . . . .
Performance Considerations . . . . . . . . . . . . . . . . . . .
Integer and Unsigned Arithmetic
. . . . . . . . . . . . . . . .
Arithmetic Operations Examples
. . . . . . . . . . . . . . . .
Array Operations . . . . . . . . . . . . . . . . . . . . . . . . . . .
Bit Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Branching Operations . . . . . . . . . . . . . . . . . . . . . . . .
Call Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Prototyped Calls . . . . . . . . . . . . . . . . . . . . . . . . . .
Operational Descriptors
. . . . . . . . . . . . . . . . . . . . .
Parsing Program Names on a Call . . . . . . . . . . . . . . .
Program CALL Example
. . . . . . . . . . . . . . . . . . .
Parsing System Built-In Names . . . . . . . . . . . . . . . . .
Value of *ROUTINE . . . . . . . . . . . . . . . . . . . . . . . .
Compare Operations . . . . . . . . . . . . . . . . . . . . . . . . .
Data-Area Operations . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . .
Date Operations
Adding or Subtracting Dates . . . . . . . . . . . . . . . . . . .
Calculating Durations between Dates
. . . . . . . . . . . . .
Unexpected Results . . . . . . . . . . . . . . . . . . . . . . . .
Declarative Operations . . . . . . . . . . . . . . . . . . . . . . . .
File Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Indicator-Setting Operations . . . . . . . . . . . . . . . . . . . . .
Information Operations . . . . . . . . . . . . . . . . . . . . . . . .
Initialization Operations . . . . . . . . . . . . . . . . . . . . . . .
Memory Management Operations . . . . . . . . . . . . . . . . .
Message Operation
. . . . . . . . . . . . . . . . . . . . . . . . .
Move Operations . . . . . . . . . . . . . . . . . . . . . . . . . . .
Moving Character, Graphic, UCS-2, and Numeric Data . . .
. . . . . . . . . . . . . . . . . . . . .
Moving Date-Time Data
Examples of Converting a Character Field to a Date Field
Move Zone Operations
. . . . . . . . . . . . . . . . . . . . . . .
String Operations . . . . . . . . . . . . . . . . . . . . . . . . . . .
Structured Programming Operations . . . . . . . . . . . . . . . .
Subroutine Operations . . . . . . . . . . . . . . . . . . . . . . . .
Coding Subroutines . . . . . . . . . . . . . . . . . . . . . . . .
Subroutine Coding Examples . . . . . . . . . . . . . . . . .
Test Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . .
|
Chapter 23. Operation Codes Detail
ACQ (Acquire)
. . . . . . . . . . . . .
ADD (Add) . . . . . . . . . . . . . . . .
ADDDUR (Add Duration) . . . . . . .
ALLOC (Allocate Storage) . . . . . . .
ANDxx (And) . . . . . . . . . . . . . .
BEGSR (Beginning of Subroutine) . .
BITOFF (Set Bits Off) . . . . . . . . .
BITON (Set Bits On) . . . . . . . . . .
CABxx (Compare and Branch) . . . .
CALL (Call a Program)
. . . . . . . .
xvi
ILE RPG for AS/400 Reference
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . .
425
427
432
433
434
434
434
435
435
436
436
437
438
438
439
440
441
441
443
445
445
446
446
447
447
449
449
450
450
452
452
452
454
456
457
458
459
462
463
463
465
467
468
469
470
472
473
474
475
476
478
480
|
|
|
CALLB (Call a Bound Procedure) . . . . . . . . . . .
CALLP (Call a Prototyped Procedure or Program) . .
CASxx (Conditionally Invoke Subroutine) . . . . . . .
CAT (Concatenate Two Strings) . . . . . . . . . . . .
CHAIN (Random Retrieval from a File) . . . . . . . .
CHECK (Check Characters)
. . . . . . . . . . . . . .
CHECKR (Check Reverse) . . . . . . . . . . . . . . .
CLEAR (Clear) . . . . . . . . . . . . . . . . . . . . . .
CLOSE (Close Files) . . . . . . . . . . . . . . . . . . .
COMMIT (Commit) . . . . . . . . . . . . . . . . . . . .
COMP (Compare) . . . . . . . . . . . . . . . . . . . .
DEALLOC (Free Storage) . . . . . . . . . . . . . . . .
DEFINE (Field Definition) . . . . . . . . . . . . . . . .
*LIKE DEFINE . . . . . . . . . . . . . . . . . . . . .
*DTAARA DEFINE . . . . . . . . . . . . . . . . . .
DELETE (Delete Record) . . . . . . . . . . . . . . . .
DIV (Divide) . . . . . . . . . . . . . . . . . . . . . . . .
DO (Do) . . . . . . . . . . . . . . . . . . . . . . . . . .
DOU (Do Until) . . . . . . . . . . . . . . . . . . . . . .
DOUxx (Do Until) . . . . . . . . . . . . . . . . . . . . .
DOW (Do While) . . . . . . . . . . . . . . . . . . . . .
DOWxx (Do While) . . . . . . . . . . . . . . . . . . . .
DSPLY (Display Function) . . . . . . . . . . . . . . . .
DUMP (Program Dump) . . . . . . . . . . . . . . . . .
ELSE (Else) . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . .
ENDyy (End a Structured Group)
ENDSR (End of Subroutine)
. . . . . . . . . . . . . .
EVAL (Evaluate expression)
. . . . . . . . . . . . . .
EVALR (Evaluate expression, right adjust) . . . . . .
EXCEPT (Calculation Time Output) . . . . . . . . . .
EXFMT (Write/Then Read Format) . . . . . . . . . . .
EXSR (Invoke Subroutine)
. . . . . . . . . . . . . . .
EXTRCT (Extract Date/Time/Timestamp) . . . . . . .
FEOD (Force End of Data) . . . . . . . . . . . . . . .
FOR (For) . . . . . . . . . . . . . . . . . . . . . . . . .
FORCE (Force a Certain File to Be Read Next Cycle)
GOTO (Go To) . . . . . . . . . . . . . . . . . . . . . .
IF (If) . . . . . . . . . . . . . . . . . . . . . . . . . . . .
IFxx (If) . . . . . . . . . . . . . . . . . . . . . . . . . . .
IN (Retrieve a Data Area) . . . . . . . . . . . . . . . .
ITER (Iterate) . . . . . . . . . . . . . . . . . . . . . . .
KFLD (Define Parts of a Key) . . . . . . . . . . . . . .
KLIST (Define a Composite Key) . . . . . . . . . . . .
LEAVE (Leave a Do/For Group) . . . . . . . . . . . .
LEAVESR (Leave a Subroutine) . . . . . . . . . . . .
LOOKUP (Look Up a Table or Array Element) . . . .
MHHZO (Move High to High Zone) . . . . . . . . . .
MHLZO (Move High to Low Zone) . . . . . . . . . . .
MLHZO (Move Low to High Zone) . . . . . . . . . . .
. . . . . . . . . . .
MLLZO (Move Low to Low Zone)
MOVE (Move) . . . . . . . . . . . . . . . . . . . . . . .
MOVEA (Move Array) . . . . . . . . . . . . . . . . . .
Character, graphic, and UCS-2 MOVEA Operations
Numeric MOVEA Operations
. . . . . . . . . . . .
. . . . . . . . . . . . . .
481
482
485
487
490
493
496
499
503
504
505
506
508
508
510
512
513
514
516
517
519
520
522
525
526
527
528
529
531
532
534
536
537
539
540
543
544
546
547
549
551
553
554
556
558
559
562
563
564
565
566
580
580
580
Contents
xvii
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . .
General MOVEA Operations . . . . . . . . . . . . .
MOVEL (Move Left) . . . . . . . . . . . . . . . . . . .
MULT (Multiply) . . . . . . . . . . . . . . . . . . . . . .
MVR (Move Remainder) . . . . . . . . . . . . . . . . .
NEXT (Next)
. . . . . . . . . . . . . . . . . . . . . . .
OCCUR (Set/Get Occurrence of a Data Structure)
.
OPEN (Open File for Processing) . . . . . . . . . . .
ORxx (Or) . . . . . . . . . . . . . . . . . . . . . . . . .
OTHER (Otherwise Select) . . . . . . . . . . . . . . .
OUT (Write a Data Area) . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . .
PARM (Identify Parameters)
PLIST (Identify a Parameter List)
. . . . . . . . . . .
POST (Post)
. . . . . . . . . . . . . . . . . . . . . . .
READ (Read a Record) . . . . . . . . . . . . . . . . .
READC (Read Next Changed Record) . . . . . . . .
READE (Read Equal Key)
. . . . . . . . . . . . . . .
READP (Read Prior Record) . . . . . . . . . . . . . .
READPE (Read Prior Equal) . . . . . . . . . . . . . .
REALLOC (Reallocate Storage with New Length) . .
REL (Release) . . . . . . . . . . . . . . . . . . . . . .
RESET (Reset) . . . . . . . . . . . . . . . . . . . . . .
Resetting Variables . . . . . . . . . . . . . . . . . .
Resetting Record Formats . . . . . . . . . . . . . .
. . . . . . . . . . . . . .
Additional Considerations
RESET Examples . . . . . . . . . . . . . . . . . . .
RETURN (Return to Caller) . . . . . . . . . . . . . . .
ROLBK (Roll Back) . . . . . . . . . . . . . . . . . . . .
SCAN (Scan String) . . . . . . . . . . . . . . . . . . .
SELECT (Begin a Select Group) . . . . . . . . . . . .
SETGT (Set Greater Than) . . . . . . . . . . . . . . .
SETLL (Set Lower Limit)
. . . . . . . . . . . . . . . .
SETOFF (Set Indicator Off) . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
SETON (Set Indicator On)
SHTDN (Shut Down) . . . . . . . . . . . . . . . . . . .
SORTA (Sort an Array) . . . . . . . . . . . . . . . . .
SQRT (Square Root) . . . . . . . . . . . . . . . . . . .
SUB (Subtract) . . . . . . . . . . . . . . . . . . . . . .
SUBDUR (Subtract Duration) . . . . . . . . . . . . . .
Subtract a duration . . . . . . . . . . . . . . . . . .
Calculate a duration . . . . . . . . . . . . . . . . . .
Possible error situations . . . . . . . . . . . . . . .
SUBDUR Examples . . . . . . . . . . . . . . . . . .
SUBST (Substring) . . . . . . . . . . . . . . . . . . . .
TAG (Tag) . . . . . . . . . . . . . . . . . . . . . . . . .
TEST (Test Date/Time/Timestamp) . . . . . . . . . .
TESTB (Test Bit) . . . . . . . . . . . . . . . . . . . . .
TESTN (Test Numeric)
. . . . . . . . . . . . . . . . .
TESTZ (Test Zone) . . . . . . . . . . . . . . . . . . . .
TIME (Retrieve Time and Date)
. . . . . . . . . . . .
UNLOCK (Unlock a Data Area or Release a Record)
Unlocking data areas . . . . . . . . . . . . . . . . .
Releasing record locks . . . . . . . . . . . . . . . .
UPDATE (Modify Existing Record) . . . . . . . . . . .
WHEN (When True Then Select)
. . . . . . . . . . .
xviii
ILE RPG for AS/400 Reference
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
581
586
596
597
598
599
603
605
606
607
608
611
613
615
618
620
623
625
628
629
630
630
631
631
632
637
640
641
644
646
650
654
655
656
657
659
660
661
661
662
663
663
664
667
668
670
672
674
675
677
677
677
679
681
WHENxx (When True Then Select) . . . . .
WRITE (Create New Records) . . . . . . . .
XFOOT (Summing the Elements of an Array)
XLATE (Translate) . . . . . . . . . . . . . . .
Z-ADD (Zero and Add) . . . . . . . . . . . . .
Z-SUB (Zero and Subtract) . . . . . . . . . .
Appendixes
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Appendix A. RPG IV Restrictions
. . . . . . . . . . . . . . . . . . . . . . . .
Appendix B. EBCDIC Collating Sequence
693
695
. . . . . . . . . . . . . . . . . . .
697
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
701
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
703
Contents
xix
Bibliography
Index
682
685
687
688
690
691
xx
ILE RPG for AS/400 Reference
Notices
This information was developed for products and services offered in the U.S.A. IBM
may not offer the products, services, or features discussed in this document in
other countries. Consult your local IBM representative for information on the products and services currently available in your area. Any reference to an IBM
product, program, or service is not intended to state or imply that only that IBM
product, program, or service may be used. Any functionally equivalent product,
program, or service that does not infringe any IBM intellectual property right may be
used instead. However, it is the user's responsibility to evaluate and verify the operation of any non-IBM product, program, or service.
IBM may have patents or pending patent applications covering subject matter
described in this document. The furnishing of this document does not give you any
license to these patents. You can send license inquiries, in writing, to:
IBM Director of Licensing
IBM Corporation
North Castle Drive
Armonk, NY 10504-1785
U.S.A.
The following paragraph does not apply to the United Kingdom or any other
country where such provisions are inconsistent with local law: INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES THIS PUBLICATION
“AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR
PURPOSE. Some states do not allow disclaimer of express or implied warranties in
certain transactions, therefore, this statement may not apply to you.
This information could include technical inaccuracies or typographical errors.
Changes are periodically made to the information herein; these changes will be
incorporated in new editions of the publication. IBM may make improvements
and/or changes in the product(s) and/or the program(s) described in this publication
at any time without notice.
Any references in this information to non-IBM Web sites are provided for convenience only and do not in any manner serve as an endorsement of those Web sites.
The materials at those Web sites are not part of the materials for this IBM product
and use of those Web sites is at your own risk.
Licensees of this program who wish to have information about it for the purpose of
enabling: (i) the exchange of information between independently created programs
and other programs (including this one) and (ii) the mutual use of the information
which has been exchanged, should contact:
IBM Canada Ltd.
Department 071
1150 Eglinton Avenue East
North York, Ontario M3C 1H7
Canada
 Copyright IBM Corp. 1994, 1999
xxi
Such information may be available, subject to appropriate terms and conditions,
including in some cases, payment of a fee.
The licensed program described in this information and all licensed material available for it are provided by IBM under terms of the IBM Customer Agreement, IBM
International Program License Agreement, or any equivalent agreement between
us.
This information contains examples of data and reports used in daily business operations. To illustrate them as completely as possible, the examples include the
names of individuals, companies, brands, and products. All of these names are
fictitious and any similarity to the names and addresses used by an actual business
enterprise is entirely coincidental.
Programming Interface Information
This publication is intended to help you create programs using RPG IV source. This
publication documents General-Use Programming Interface and Associated Guidance Information provided by the ILE RPG for AS/400 compiler.
General-Use programming interfaces allow the customer to write programs that
obtain the services of the ILE RPG for AS/400 compiler.
Trademarks and Service Marks
The following terms are trademarks of the International Business Machines Corporation in the United States or other countries or both:
400
Application System/400
AS/400
DB2
IBM
IBMLink
Integrated Language Environment
Operating System/400
OS/400
PROFS
RPG/400
System/36
Domino is a trademark of the Lotus Development Corporation in the United States,
or other countries, or both.
Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and/or other countries.
UNIX is a registered trademark in the United States and/or other countries licensed
exclusively through X/Open Company Limited.
Other company, product, and service names may be the trademarks or service
marks of others.
Registered trademarks and unregistered trademarks are denoted by  and 
respectively.
xxii
ILE RPG for AS/400 Reference
About This Reference
This reference provides information about the RPG IV language as it is implemented using the ILE RPG for AS/400 compiler (ILE RPG) with the Operating
System/400 (OS/400) operating system.
This reference covers:
¹ RPG IV character set
¹ Symbolic names
¹ Special words
¹ RPG IV cycle
¹ Error handling
¹ Subprocedures
¹ Definitions
¹ RPG IV specifications
¹ Built-in functions
¹ Expressions
¹ Operation codes
Who Should Use This Reference
This reference is for programmers who are familiar with the RPG IV programming
language.
This reference provides a detailed description of the RPG IV language. It does not
provide information on how to use the ILE RPG compiler or converting RPG III programs to ILE RPG. For information on those subjects, see the ILE RPG for AS/400
Programmer's Guide, SC09-2507-02.
Before using this reference, you should
¹ Know how to use applicable AS/400 menus and displays or Control Language
(CL) commands.
¹ Have a firm understanding of Integrated Language Environment as described
in detail in the ILE Concepts, SC41-5606-03.
Prerequisite and Related Information
Use the AS/400 Information Center as your starting point for looking up AS/400
technical information. You can access the Information Center from the AS/400e
Information Center CD-ROM (English version: SK3T-2027-01) or from one of these
Web sites:
http://www.as400.ibm.com/infocenter
http://publib.boulder.ibm.com/pubs/html/as400/infocenter.htm
The AS/400 Information Center contains important topics such as logical partitioning, clustering, Java, TCP/IP, Web serving, and secured networks. It also con Copyright IBM Corp. 1994, 1999
xxiii
tains Internet links to Web sites such as the AS/400 Online Library and the AS/400
Technical Studio. Included in the Information Center is a link that describes at a
high level the differences in information between the Information Center and the
Online Library.
For a list of related publications, see the “Bibliography” on page 701.
How to Send Your Comments
Your feedback is important in helping to provide the most accurate and high-quality
information. IBM welcomes any comments about this book or any other AS/400
documentation.
¹ If you prefer to send comments by mail, use the the following address:
IBM Canada Ltd. Laboratory
Information Development
2G/KB7/1150/TOR
1150 Eglinton Avenue East
North York, Ontario, Canada M3C 1H7
If you are mailing a readers' comment form from a country other than the
United States, you can give the form to the local IBM branch office or IBM representative for postage-paid mailing.
¹ If you prefer to send comments by FAX, use the following number:
– 1-416-448-6161
¹ If you prefer to send comments electronically, use one of these e-mail
addresses:
– Comments on books:
torrcf@ca.ibm.com
IBMLink: toribm(torrcf)
– Comments on the AS/400 Information Center:
RCHINFOC@us.ibm.com
Be sure to include the following:
¹ The name of the book.
¹ The publication number of the book.
¹ The page number or topic to which your comment applies.
|
What's New This Release?
|
|
|
|
|
The major enhancements to RPG IV since V4R2 are the support for running ILE
RPG modules safely in a threaded environment, the new 3-digit and 20-digit signed
and unsigned integer data types, and support for a new Universal Character Set
Version 2 (UCS-2) data type and for conversion between UCS-2 fields and graphic
or single-byte character fields.
|
The following list describes these enhancements:
¹ Support for calling ILE RPG procedures from a threaded application, such as
Domino or Java.
|
|
xxiv
ILE RPG for AS/400 Reference
|
|
|
|
|
– The new control specification keyword THREAD(*SERIALIZE) identifies
modules that are enabled to run in a multithreaded environment. Access to
procedures in the module is serialized.
¹ Support for new 1-byte and 8-byte integer data types: 3I and 20I signed
integer, and 3U and 20U unsigned integer
|
|
|
– These new integer data types provide you with a greater range of integer
values and can also improve performance of integer computations, taking
full advantage of the 64-bit AS/400 RISC processor.
|
|
|
– The new 3U type allows you to more easily communicate with ILE C procedures that have single-byte character (char) return types and parameters
passed by value.
|
|
|
– The new INTPREC control specification keyword allows you to specify
20-digit precision for intermediate values of integer and unsigned binary
arithmetic operations in expressions.
|
|
– Built-in functions %DIV and %REM have been added to support integer
division and remainder operations.
|
|
¹ Support for new Universal Character Set Version 2 (UCS-2) or Unicode data
type
|
|
|
– The UCS-2 (Unicode) character set can encode the characters for many
written languages. The field is a character field whose characters are two
bytes long.
|
|
|
|
– By adding support for Unicode, a single application can now be developed
for a multinational corporation, minimizing the necessity to perform code
page conversion. The use of Unicode permits the processing of characters
in multiple scripts without loss of integrity.
|
|
|
– Support for conversions between UCS-2 fields and graphic or single-byte
character fields using the MOVE and MOVEL operations, and the new
%UCS2 and %GRAPH built-in functions.
|
|
|
– Support for conversions between UCS-2 fields or graphic fields with different Coded Character Set Identifiers (CCSIDs) using the EVAL, MOVE,
and MOVEL operations, and the new %UCS2 built-in function.
|
|
|
Other enhancements have been made to this release as well. These include:
¹ New parameters for the OPTION control specification keyword and on the
create commands:
|
|
|
|
|
|
– *SRCSTMT allows you to assign statement numbers for debugging from
the source IDs and SEU sequence numbers in the compiler listing. (The
statement number is used to identify errors in the compiler listing by the
debugger, and to identify the statement where a run-time error occurs.)
*NOSRCSTMT specifies that statement numbers are associated with the
Line Numbers of the listing and the numbers are assigned sequentially.
|
|
|
|
– Now you can choose not to generate breakpoints for input and output specifications in the debug view with *NODEBUGIO. If this option is selected, a
STEP on a READ statement in the debugger will step to the next calculation, rather than stepping through the input specifications.
|
¹ New special words for the INZ definition specification keyword:
About This Reference
xxv
|
|
– INZ(*EXTDFT) allows you to use the default values in the DDS for initializing externally described data structure subfields.
|
|
– Character variables initialized by INZ(*USER) are initialized to the name of
the current user profile.
|
|
¹ The new %XFOOT built-in function sums all elements of a specified array
expression.
|
|
|
¹ The new EVALR operation code evaluates expressions and assigns the result
to a fixed-length character or graphic result. The assignment right-adjusts the
data within the result.
|
|
¹ The new FOR operation code performs an iterative loop and allows free-form
expressions for the initial, increment, and limit values.
|
|
¹ The new LEAVESR operation code can be used to exit from any point within a
subroutine.
|
|
¹ The new *NEXT parameter on the OVERLAY(name:*NEXT) keyword indicates
that a subfield overlays another subfield at the next available position.
|
|
¹ The ability to use hexadecimal literals with integer and unsigned integer fields
in initialization and free-form operations, such as EVAL, IF, etc.
|
|
|
¹ New control specification keyword OPENOPT{(*NOINZOFL | *INZOFL)} to indicate whether the overflow indicators should be reset to *OFF when a file is
opened.
|
|
¹ Ability to tolerate pointers in teraspace — a memory model that allows more
than 16 megabytes of contiguous storage in one allocation.
|
|
The following tables summarize the changed and new language elements, based
on the part of the language affected.
|
Table 1 (Page 1 of 2). Changed Language Elements Since V4R2
|
Language Unit
Element
Description
|
|
|
|
|
|
|
|
Control specification keywords
OPTION(*{NO}SRCSTMT)
*SRCSTMT allows you to request
that the compiler use SEU sequence
numbers and source IDs when generating statement numbers for
debugging. Otherwise, statement
numbers are associated with the
Line Numbers of the listing and the
numbers are assigned sequentially.
OPTION(*{NO}DEBUGIO)
*{NO}DEBUGIO, determines if breakpoints are generated for input and
output specifications.
|
|
|
xxvi
ILE RPG for AS/400 Reference
|
Table 1 (Page 2 of 2). Changed Language Elements Since V4R2
|
Language Unit
Element
Description
|
|
|
|
Definition specification
keywords
INZ(*EXTDFT)
All externally described data structure subfields can now be intialized
to the default values specified in the
DDS.
|
|
|
INZ(*USER)
Any character field or subfield can
be initialized to the name of the
current user profile.
|
|
|
|
OVERLAY(name:*NEXT)
The special value *NEXT indicates
that the subfield is to be positioned
at the next available position within
the overlayed field.
|
|
|
|
|
|
|
OPTIONS(*NOPASS
*OMIT *VARSIZE
*STRING *RIGHTADJ)
The new OPTIONS(*RIGHTADJ)
specified on a value or constant
parameter in a function prototype
indicates that the character, graphic,
or UCS-2 value passed as a parameter is to be right adjusted before
being passed on the procedure call.
|
|
|
|
Definition specification positions 33-39 (To
Position/Length)
3 and 20 digits allowed for
I and U data types
Added to the list of allowed values
for internal data types to support
1-byte and 8-byte integer and
unsigned data.
|
|
|
|
|
|
|
Internal data
type
C (UCS-2 fixed or
variable-length format)
Added to the list of allowed internal
data types on the definition specifications. The UCS-2 (Unicode) character set can encode the characters
for many written languages. The field
is a character field whose characters
are two bytes long.
|
|
|
|
Data format
C (UCS-2 fixed or
variable-length format)
UCS-2 format added to the list of
allowed data formats on the input
and output specifications for program
described files.
|
|
|
|
|
Command
parameter
OPTION
*NOSRCSTMT, *SRCSTMT,
*NODEBUGIO, and *DEBUGIO have
been added to the OPTION parameter on the CRTBNDRPG and
CRTRPGMOD commands.
About This Reference
xxvii
|
Table 2 (Page 1 of 2). New Language Elements Since V4R2
Language Unit
Element
Description
Control specification keywords
CCSID(*GRAPH:
*IGNORE | *SRC |
number)
Sets the default graphic CCSID for
the module. This setting is used for
literals, compile-time data and
program-described input and output
fields and definitions. The default is
*IGNORE.
|
|
|
|
|
|
CCSID(*UCS2: number)
Sets the default UCS-2 CCSID for
the module. This setting is used for
literals, compile-time data and
program-described input and output
fields and definitions. The default is
13488.
|
|
|
|
|
|
INTPREC(10 | 20)
Specifies the decimal precision of
integer and unsigned intermediate
values in binary arithmetic operations
in expressions. The default,
INTPREC(10), indicates that 10-digit
precision is to be used.
|
|
|
OPENOPT{(*NOINZOFL |
*INZOFL)}
Indicates whether the overflow indicators should be reset to *OFF when
a file is opened.
|
|
|
|
THREAD(*SERIALIZE)
Indicates that the module is enabled
to run in a multithreaded environment. Access to the procedures in
the module is to be serialized.
|
|
|
|
|
|
|
|
|
Definition specification
keywords
CCSID(number | *DFT)
Sets the graphic and UCS-2 CCSID
for the definition.
|
|
|
|
|
Built-in functions
%DIV(n:m)
Performs integer division on the two
operands n and m; the result is the
integer portion of n/m. The operands
must be numeric values with zero
decimal positions.
|
|
|
%GRAPH(char-expr |
graph-expr | UCS2-expr {:
ccsid})
Converts to graphic data from singlebyte character, graphic, or UCS-2
data.
|
|
|
|
|
%REM(n:m)
Performs the integer remainder operation on two operands n and m; the
result is the remainder of n/m. The
operands must be numeric values
with zero decimal positions.
|
|
|
%UCS2(char-expr | graphexpr | UCS2-expr {: ccsid})
Converts to UCS-2 data from singlebyte character, graphic, or UCS-2
data.
|
|
|
%XFOOT(array-expr)
Produces the sum of all the elements in the specified numeric array
expression.
xxviii
ILE RPG for AS/400 Reference
Changes to this Reference Since V4R2
|
Table 2 (Page 2 of 2). New Language Elements Since V4R2
|
Language Unit
Element
Description
|
|
|
Operation codes
EVALR
Evaluates an assignment statement
of the form result=expression. The
result will be right-justified.
|
|
|
|
|
FOR
Begins a group of operations and
indicates the number of times the
group is to be processed. The initial,
increment, and limit values can be
free-form expressions.
|
|
ENDFOR
ENDFOR ends a group of operations
started by a FOR operation.
|
|
LEAVESR
Used to exit from anywhere within a
subroutine.
|
|
|
|
|
|
|
Changes to this Reference Since V4R2
This V4R4 reference, ILE RPG for AS/400 Reference, SC09-2508-02, differs in
many places from the V4R2 reference, ILE RPG for AS/400 Reference,
SC09-2508-01. Most of the changes are related to the enhancements that have
been made since V4R2; others reflect minor technical corrections. To assist you in
using this manual, technical changes and enhancements are noted with a vertical
bar (|).
About This Reference
xxix
Changes to this Reference Since V4R2
xxx
ILE RPG for AS/400 Reference
RPG IV Concepts
This section describes some of the basics of RPG IV:
¹ Symbolic names
¹ Compiler directives
¹ RPG IV program cycle
¹ Indicators
¹ Error Handling
¹ Subprocedures
¹ General file considerations
 Copyright IBM Corp. 1994, 1999
1
2
ILE RPG for AS/400 Reference
Symbolic Names
Chapter 1. Symbolic Names and Reserved Words
The valid character set for the RPG IV language consists of:
¹ The letters A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
¹ RPG IV accepts lowercase letters in symbolic names but translates them to
uppercase during compilation
¹ The numbers 0 1 2 3 4 5 6 7 8 9
¹ The characters + − * , . ' & / $ # : @ _ > < = ( ) %
¹ The blank character
Note: The $, #, and @ may appear as different symbols on some codepages. For
more information, see the National Language Support, SC41-5101-01.
Symbolic Names
A symbolic name is a name that uniquely identifies a specific entity in a program or
procedure. In the RPG IV language, symbolic names are used for the following:
¹ Arrays (on page 4)
¹ Conditional compile names (on page 4)
¹ Data structures (on page 4)
¹ Exception output records (on page 4)
¹ Fields (on page 4)
¹ Key field lists (on page 4)
¹ Labels (on page 5)
¹ Named constants (on page 121)
¹ Parameter lists (on page 5)
¹ Prototype names (on page 5)
¹ Record names (on page 5)
¹ Subroutines (on page 5)
¹ Tables (on page 5).
The following rules apply to all symbolic names except for deviations noted in the
description of each symbolic name:
¹ The first character of the name must be alphabetic. This includes the characters $, #, and @.
¹ The remaining characters must be alphabetic or numeric. This includes the
underscore (_).
¹ The name must be left-adjusted in the entry on the specification form except in
fields which allow the name to float (definition specification, keyword fields, and
the extended factor 2 field).
¹ A symbolic name cannot be an RPG IV reserved word.
 Copyright IBM Corp. 1994, 1999
3
Symbolic Names
¹ A symbolic name can be from 1 to 4096 characters. The practical limits are
determined by the size of the entry used for defining the name. A name that is
up to 15 characters can be specified in the Name entry of the definition or procedure specification. For names longer than 15 characters, use a continuation
specification. For more information, see Chapter 12, “About Specifications” on
page 221.
¹ A symbolic name must be unique within the procedure in which it is defined.
Array Names
The following additional rule applies to array names:
¹ An array name cannot begin with the letters TAB.
Conditional Compile Names
The symbolic names used for conditional compilation have no relationship to other
symbolic names. For example, if you define a file called MYFILE, you may later use
/DEFINE to define condition name MYFILE, and you may also use /UNDEFINE to
remove condition name MYFILE. This has no effect on the file name MYFILE.
Conditional compile names can be up to 50 characters long.
Data Structure Names
A data structure is an area in storage and is considered to be a character field.
EXCEPT Names
An EXCEPT name is a symbolic name assigned to an exception output record. The
following additional rule applies to EXCEPT names:
¹ The same EXCEPT name can be assigned to more than one output record.
Field Names
The following additional rules apply to field names:
¹ A field name can be defined more than once if each definition using that name
has the same data type, the same length, and the same number of decimal
positions. All definitions using the same name refer to a single field (that is, the
same area in storage). However, it can be defined only once on the definition
specification.
¹ A field can be defined as a data structure subfield only once.
¹ A subfield name cannot be specified as the result field on an *ENTRY PLIST
parameter.
KLIST Names
A KLIST name is a symbolic name assigned to a list of key fields.
4
ILE RPG for AS/400 Reference
RPG IV Words with Special Functions/Reserved Words
Labels
A label is a symbolic name that identifies a specific location in a program (for
example, the name assigned to a TAG or ENDSR operation).
Named Constants
A named constant is a symbolic name assigned to a constant.
PLIST Names
A PLIST name is a symbolic name assigned to a list of parameters.
Prototype Names
A prototype name is a symbolic name assigned to a prototype definition. This name
must be used when calling a prototyped procedure or program.
Record Names
A record name is a symbolic name assigned to a record format in an externally
described file. The following additional rules apply to record names in an RPG IV
program:
¹ A record name can exist in only one file in the program.
Note: See “RENAME(Ext_format:Int_format)” on page 269 for information on how
to overcome this limitation.
Subroutine Names
The name is defined in factor 1 of the BEGSR (begin subroutine) operation.
Table Names
The following additional rules apply to table names:
¹ A table name can contain from 3 to 10 characters.
¹ A table name must begin with the letters TAB.
¹ A table cannot be defined in a subprocedure.
RPG IV Words with Special Functions/Reserved Words
The RPG IV reserved words listed below have special functions within a program.
¹ The following reserved words allow you to access the job date, or a portion of
it, to be used in the program:
UDATE
*DATE
UMONTH
*MONTH
UYEAR
*YEAR
UDAY
Chapter 1. Symbolic Names and Reserved Words
5
RPG IV Words with Special Functions/Reserved Words
*DAY
¹ The following reserved words can be used for numbering the pages of a report,
for record sequence numbering, or to sequentially number output fields:
PAGE
PAGE1-PAGE7
¹ Figurative constants are implied literals that allow specifications without referring to length:
*BLANK/*BLANKS
*ZERO/*ZEROS
*HIVAL
*LOVAL
*NULL
*ON
*OFF
*ALLX'x1..'
*ALLG'oK1K2i'
*ALL'X..'
¹ The following reserved words are used for positioning database files. *START
positions to beginning of file and *END positions to end of file.
*END
*START
¹ The following reserved words allow RPG IV indicators to be referred to as data:
*IN
*INxx
¹ The following are special words used with date and time:
*CDMY
*CMDY
*CYMD
*DMY
*EUR
*HMS
*ISO
*JIS
*JOB
*JOBRUN
*JUL
*LONGJUL
*MDY
6
ILE RPG for AS/400 Reference
User Date Special Words
*SYS
*USA
*YMD
¹ The following are special words used with translation:
*ALTSEQ
*EQUATE
*FILE
*FTRANS
¹ *PLACE allows repetitive placement of fields in an output record. (See
“*PLACE” on page 343 for more information.)
¹ *ALL allows all fields that are defined for an externally described file to be
written on output. (See “Rules for Figurative Constants” on page 123 for more
information on *ALL)
¹ The following are special words used within expressions:
AND
NOT
OR
Note: NOT can only be used within expressions. It cannot be used as a
name anywhere in the source.
¹ The following are special words used with parameter passing:
*OMIT
|
*NOPASS
|
*VARSIZE
|
*STRING
|
*RIGHTADJ
User Date Special Words
The user date special words (UDATE, *DATE, UMONTH, *MONTH, UDAY, *DAY,
UYEAR, *YEAR) allow the programmer to supply a date for the program at run
time. The user date special words access the job date that is specified in the job
description. The user dates can be written out at output time; UDATE and *DATE
can be written out using the Y edit code in the format specified by the control specification.
(For a description of the job date, see theWork Management manual.)
Rules for User Date
Remember the following rules when using the user date:
¹ UDATE, when specified in positions 30 through 43 of the output specifications,
prints a 6-character numeric date field. *DATE, when similarly specified, prints
an 8-character (4-digit year portion) numeric date field. These special words
can be used in three different date formats:
Chapter 1. Symbolic Names and Reserved Words
7
PAGE, PAGE1-PAGE7
Month/day/year
Year/month/day
Day/month/year
Use the DATEDIT keyword on the control specification to specify the editing to
be done. If this keyword is not specified, the default is *MDY.
¹ For an interactive job or batch program, the user date special words are set to
the value of the job date when the program starts running in the system. The
value of the user date special words are not updated during program processing, even if the program runs past midnight or if the job date is changed.
Use the TIME operation code to obtain the time and date while the program is
running.
¹ UMONTH, *MONTH, UDAY, *DAY, and UYEAR when specified in positions 30
through 43 of the output specifications, print a 2-position numeric date field.
*YEAR can be used to print a 4-position numeric date field. Use UMONTH or
*MONTH to print the month only, UDAY or *DAY to print the day only, and
UYEAR or *YEAR to print the year only.
¹ UDATE and *DATE can be edited when they are written if the Y edit code is
specified in position 44 of the output specifications. The
“DATEDIT(fmt{separator})” on page 238 keyword on the control specification
determines the format and the separator character to be inserted; for example,
12/31/88, 31.12.88., 12/31/1988.
¹ UMONTH, *MONTH, UDAY, *DAY, UYEAR and *YEAR cannot be edited by
the Y edit code in position 44 of the output specifications.
¹ The user date fields cannot be modified. This means they cannot be used:
– In the result field of calculations
– As factor 1 of PARM operations
– As the factor 2 index of LOOKUP operations
– With blank after in output specifications
– As input fields
¹ The user date special words can be used in factor 1 or factor 2 of the calculation specifications for operation codes that use numeric fields.
¹ User date fields are not date data type fields but are numeric fields.
PAGE, PAGE1-PAGE7
PAGE is used to number the pages of a report, to serially number the output
records in a file, or to sequentially number output fields. It does not cause a page
eject.
The eight possible PAGE fields (PAGE, PAGE1, PAGE2, PAGE3, PAGE4, PAGE5,
PAGE6, and PAGE7) may be needed for numbering different types of output pages
or for numbering pages for different printer files.
PAGE fields can be specified in positions 30 through 43 of the output specifications
or in the input or calculation specifications.
8
ILE RPG for AS/400 Reference
PAGE, PAGE1-PAGE7
Rules for PAGE, PAGE1-PAGE7
Remember the following rules when using the PAGE fields:
¹ When a PAGE field is specified in the output specifications, without being
defined elsewhere, it is assumed to be a four-digit, numeric field with zero
decimal positions.
¹ Page numbering, unless otherwise specified, starts with 0001; and 1 is automatically added for each new page.
¹ To start at a page number other than 1, set the value of the PAGE field to one
less than the starting page number. For example, if numbering starts with 24,
enter a 23 in the PAGE field. The PAGE field can be of any length but must
have zero decimal positions (see Figure 1).
¹ Page numbering can be restarted at any point in a job. The following methods
can be used to reset the PAGE field:
– Specify blank-after (position 45 of the output specifications).
– Specify the PAGE field as the result field of an operation in the calculation
specifications.
– Specify an output indicator in the output field specifications (see Figure 2).
When the output indicator is on, the PAGE field will be reset to 1. Output
indicators cannot be used to control the printing of a PAGE field, because a
PAGE field is always written.
– Specify the PAGE field as an input field as shown in Figure 1.
¹ Leading zeros are automatically suppressed (Z edit code is assumed) when a
PAGE field is printed unless an edit code, edit word, or data format (P/B/L/R in
position 52) has been specified. Editing and the data format override the suppression of leading zeros. When the PAGE field is defined in input and calculation specifications, it is treated as a field name in the output specifications
and zero suppression is not automatic.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................
I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr....
IINPUT
PG 50
1 CP
I
2
5 0PAGE
Figure 1. Page Record Description
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
OFilename++DF..N01N02N03Excnam++++B++A++Sb+Sa+...........................
O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat
O* When indicator 15 is on, the PAGE field is set to zero and 1 is
O* added before the field is printed. When indicator 15 is off, 1
O* is added to the contents of the PAGE field before it is printed.
OPRINT
H
L1
01
O
15
PAGE
1
75
Figure 2. Resetting the PAGE Fields to Zero
Chapter 1. Symbolic Names and Reserved Words
9
PAGE, PAGE1-PAGE7
10
ILE RPG for AS/400 Reference
/EJECT (Positions 7-12)
Chapter 2. Compiler Directives
The compiler directive statements /TITLE, /EJECT, /SPACE, and /COPY allow you
to specify heading information for the compiler listing, to control the spacing of the
compiler listing, and to insert records from other file members during a compile.
The conditional compilation directive statements /DEFINE, /UNDEFINE, /IF,
/ELSEIF, /ELSE, /ENDIF, and /EOF allow you to select or omit source records. The
compiler directive statements must precede any compile-time array or table
records, translation records, and alternate collating sequence records (that is, **
records).
/TITLE (Positions 7-12)
Use the compiler directive /TITLE to specify heading information (such as security
classification or titles) that is to appear at the top of each page of the compiler
listing. The following entries are used for /TITLE:
Positions Entry
7-12
/TITLE
13
Blank
14-100
Title information
A program can contain more than one /TITLE statement. Each /TITLE statement
provides heading information for the compiler listing until another /TITLE statement
is encountered. A /TITLE statement must be the first RPG specification encountered to print information on the first page of the compiler listing. The information
specified by the /TITLE statement is printed in addition to compiler heading information.
The /TITLE statement causes a skip to the next page before the title is printed. The
/TITLE statement is not printed on the compiler listing.
/EJECT (Positions 7-12)
Positions Entry
7-12
/EJECT
13-49
Blank
50-100
Comments
Enter /EJECT in positions 7 through 12 to indicate that subsequent specifications
are to begin on a new page of the compiler listing. Positions 13 through 49 of the
/EJECT statement must be blank. The remaining positions may be used for comments. If the spool file is already at the top of a new page, /EJECT will not advance
to a new page. /EJECT is not printed on the compiler listing.
 Copyright IBM Corp. 1994, 1999
11
/COPY (Positions 7-11)
/SPACE (Positions 7-12)
Use the compiler directive /SPACE to control line spacing within the source section
of the compiler listing. The following entries are used for /SPACE:
Positions Entry
7-12
/SPACE
13
Blank
14-16
A positive integer value from 1 through 112 that defines the number of
lines to space on the compiler listing. The number must be left-adjusted.
17-49
Blank
50-100
Comments
If the number specified in positions 14 through 16 is greater 112, 112 will be used
as the /SPACE value. If the number specified in positions 14 through 16 is greater
than the number of lines remaining on the current page, subsequent specifications
begin at the top of the next page.
/SPACE is not printed on the compiler listing, but is replaced by the specified line
spacing. The line spacing caused by /SPACE is in addition to the two lines that are
skipped between specification types.
/COPY (Positions 7-11)
The /COPY compiler directive causes records from other files to be inserted, at the
point where the /COPY occurs, with the file being compiled. The inserted files may
contain any valid specification including /COPY up to the maximum nesting depth
specified by the COPYNEST keyword (32 when not specified).
The /COPY statement is entered in the following way:
Positions Entry
7-11
/COPY
12
Blank
13-49
Identifies the location of the member to be copied (merged). The format
is:
libraryname/filename,membername
¹ A member name must be specified.
¹ If a file name is not specified, QRPGLESRC is assumed.
¹ If a library is not specified, the library list is searched for the file. All
occurrences of the specified source file in the library list are
searched for the member until it is located or the search is complete.
¹ If a library is specified, a file name must also be specified.
50-100
12
ILE RPG for AS/400 Reference
Comments
/COPY (Positions 7-11)
TIP
To facilitate application maintenance, you may want to place the prototypes of
exported procedures in a /COPY member. If you do, be sure to place a /COPY
directive for that member in both the module containing the exported procedure
and any modules that contain calls to the exported procedure.
Figure 3 shows some examples of the /COPY directive statement.
C/COPY MBR1 .1/
I/COPY SRCFIL,MBR2 .2/
O/COPY SRCLIB/SRCFIL,MBR3 .3/
O/COPY "SRCLIB!"/"SRC>3","MBR¬3" .4/
Figure 3. Examples of the /COPY Compiler Directive Statement
.1/
Copies from member MBR1 in source file QRPGLESRC. The current
library list is used to search for file QRPGLESRC.
.2/
Copies from member MBR2 in file SRCFIL. The current library list is
used to search for file SRCFIL. Note that the comma is used to separate
the file name from the member name.
.3/
Copies from member MBR3 in file SRCFIL in library SRCLIB.
.4/
Copies from member "MBR¬3" in file "SRC>3" in library "SRCLIB!"
Results of the /COPY during Compile
During compilation, the specified file members are merged into the program at the
point where the /COPY statement occurs. All /COPY members will appear in the
COPY member table.
Nested /COPY
Nesting of /COPY directives is allowed. A /COPY member may contain one or more
/COPY directives (which in turn may contain further /COPY directives and so on).
The maximum depth to which nesting can occur can be set using the COPYNEST
control specification keyword. The default maximum depth is 32.
TIP
You must ensure that your nested /COPY files do not include each other infinitely. Use conditional compilation directives at the beginning of your /COPY
files to prevent the source lines from being used more than once.
For an example of how to prevent multiple inclusion, see Figure 4 on page 17.
Chapter 2. Compiler Directives
13
Conditional Compilation Directives
Conditional Compilation Directives
The conditional compilation directive statements allow you to conditionally include
or exclude sections of source code from the compile.
¹ Condition-names can be added or removed from a list of currently defined conditions using the defining condition directives /DEFINE and /UNDEFINE.
¹ Condition expressions DEFINED(condition-name) and NOT
DEFINED(condition-name) are used within testing condition /IF groups.
¹ Testing condition directives, /IF, /ELSEIF, /ELSE and /ENDIF, control which
source lines are to be read by the compiler.
¹ The /EOF directive tells the compiler to ignore the rest of the source lines in the
current source member.
Defining Conditions
Condition-names can be added to or removed from a list of currently defined conditions using the defining condition directives /DEFINE and /UNDEFINE.
/DEFINE (Positions 7-13)
The /DEFINE compiler directive defines conditions for conditional compilation. The
entries in the condition-name area are free-format (do not have to be left justified).
The following entries are used for /DEFINE:
Positions Entry
7 - 13
/DEFINE
14
Blank
15 - 80
condition-name
81 - 100
Comments
The /DEFINE directive adds a condition-name to the list of currently defined conditions. A subsequent /IF DEFINED(condition-name) would be true. A subsequent /IF
NOT DEFINED(condition-name) would be false.
Note: The command parameter DEFINE can be used to predefine up to 32 conditions on the CRTBNDRPG and CRTRPGMOD commands.
/UNDEFINE (Positions 7-15)
Use the /UNDEFINE directive to indicate that a condition is no longer defined. The
entries in the condition-name area are free-format (do not have to be left justified).
Positions Entry
7 - 15
/UNDEFINE
16
Blank
17 - 80
condition-name
81 - 100
Comments
The /UNDEFINE directive removes a condition-name from the list of currently
defined conditions. A subsequent /IF DEFINED(condtion-name) would be false. A
subsequent /IF NOT DEFINED(condition-name) would be true.
14
ILE RPG for AS/400 Reference
Conditional Compilation Directives
Note: Any conditions specified on the DEFINE parameter will be considered to be
defined when processing /IF and /ELSEIF directives. These conditions can
be removed using the /UNDEFINE directive.
Condition Expressions
A condition expression has one of the following forms:
¹ DEFINED(condition-name)
¹ NOT DEFINED(condition-name)
The condition expression is free-format but cannot be continued to the next line.
Testing Conditions
Conditions are tested using /IF groups, consisting of an /IF directive, followed by
zero or more /ELSEIF directives, followed optionally by an /ELSE directive, followed
by an /ENDIF directive.
Any source lines except compile-time data, are valid between the directives of an
/IF group. This includes nested /IF groups.
Note: There is no practical limit to the nesting level of /IF groups.
/IF Condition-Expression (Positions 7-9)
The /IF compiler directive is used to test a condition expression for conditional compilation. The following entries are used for /IF:
Positions Entry
7-9
/IF
10
Blank
11 - 80
Condition expression
81 - 100
Comments
If the condition expression is true, source lines following the /IF directive are
selected to be read by the compiler. Otherwse, lines are excluded until the next
/ELSEIF, /ELSE or /ENDIF in the same /IF group.
/ELSEIF Condition-Expression (Positions 7-13)
The /ELSEIF compiler directive is used to test a condition expression within an /IF
or /ELSEIF group. The following entries are used for /ELSEIF:
Positions Entry
7 - 13
/ELSEIF
14
Blank
15 - 80
Condition expression
81 - 100
Comments
If the previous /IF or /ELSEIF was not satisfied, and the condition expression is
true, then source lines following the /ELSEIF directive are selected to be read. Otherwise, lines are excluded until the next /ELSEIF, /ELSE or /ENDIF in the same /IF
group is encountered.
Chapter 2. Compiler Directives
15
Conditional Compilation Directives
/ELSE (Positions 7-11)
The /ELSE compiler directive is used to unconditionally select source lines to be
read following a failed /IF or /ELSEIF test. The following entries are used for /ELSE:
Positions Entry
7 - 11
/ELSE
12 - 80
Blank
81 - 100
Comments
If the previous /IF or /ELSEIF was not satisfied, source lines are selected until the
next /ENDIF.
If the previous /IF or /ELSEIF was satisfied, source lines are excluded until the next
/ENDIF.
/ENDIF (Positions 7-12)
The /ENDIF compiler directive is used to end the most recent /IF, /ELSEIF or
/ELSE group. The following entries are used for /ENDIF:
Positions Entry
7 - 12
/ENDIF
13 - 80
Blank
81 - 100
Comments
Following the /ENDIF directive, if the matching /IF directive was a selected line,
lines are unconditionally selected. Otherwise, the entire /IF group was not selected,
so lines continue to be not selected.
Rules for Testing Conditions
¹ /ELSEIF, and /ELSE are not valid outside an /IF group.
¹ An /IF group can contain at most one /ELSE directive. An /ELSEIF directive
cannot follow an /ELSE directive.
¹ /ENDIF is not valid outside an /IF, /ELSEIF or /ELSE group.
¹ Every /IF must be matched by a subsequent /ENDIF.
¹ All the directives associated with any one /IF group must be in the same source
file. It is not valid to have /IF in one file and the matching /ENDIF in another,
even if the second file is in a nested /COPY. However, a complete /IF group
can be in a nested /COPY.
The /EOF Directive
The /EOF directive tells the compiler to ignore the rest of the source lines in the
current source member.
/EOF (Positions 7-10)
The /EOF compiler directive is used to indicate that the compiler should consider
that end-of-file has been reached for the current source file. The following entries
are used for /EOF:
16
ILE RPG for AS/400 Reference
Conditional Compilation Directives
Positions Entry
7 - 10
/EOF
11 - 80
Blank
81 - 100
Comments
/EOF will end any active /IF group that became active during the reading of the
current source member. If the /EOF was in a /COPY file, then any conditions that
that were active when the /COPY directive was read will still be active.
Note: If excluded lines are being printed on the listing, the source lines will continue to be read and listed after /EOF, but the content of the lines will be
completely ignored by the compiler. No diagnostic messages will ever be
issued after /EOF.
TIP
Using the /EOF directive will enhance compile-time performance when an entire
/COPY member is to be used only once, but may be copied in multiple times.
(This is not true if excluded lines are being printed).
The following is an example of the /EOF directive.
*----------------------------------------------------------------* Main source file
*----------------------------------------------------------------....
/IF DEFINED(READ_XYZ)
.1./
/COPY XYZ
/ENDIF
.2./
....
*----------------------------------------------------------------* /COPY file XYZ
*----------------------------------------------------------------/IF DEFINED(XYZ_COPIED)
.3./
/EOF
/ELSE
/DEFINE XYZ_COPIED
D .....
/ENDIF
Figure 4. /EOF Directive
The first time this /COPY member is read, XYZ_COPIED will not be defined, so the
/EOF will not be considered.
The second time this member is read, XYZ_COPIED is defined, so the /EOF is
processed. The /IF DEFINED(XYZ_COPIED) (.3./) is considered ended, and the
file is closed. However, the /IF DEFINED(READ_XYZ) (.1./) from the main source
member is still active until its own /ENDIF (.2./) is reached.
Chapter 2. Compiler Directives
17
Conditional Compilation Directives
18
ILE RPG for AS/400 Reference
General RPG IV Program Cycle
Chapter 3. Program Cycle
The ILE RPG compiler supplies part of the logic for an RPG program. The logic the
compiler supplies is called the program cycle or logic cycle. The program cycle is a
series of ordered steps that the main procedure goes through for each record read.
The information that you code on RPG IV specifications in your source program
need not explicitly specify when records should be read or written. The ILE RPG
compiler can supply the logical order for these operations when your source
program is compiled. Depending on the specifications you code, your program may
or may not use each step in the cycle.
Primary (identified by a P in position 18 of the file description specifications) and
secondary (identified by an S in position 18 of the file description specifications)
files indicate input is controlled by the program cycle. A full procedural file (identified by an F in position 18 of the file description specifications) indicates that input
is controlled by program-specified calculation operations (for example, READ and
CHAIN).
To control the cycle, you can have:
¹ One primary file and, optionally, one or more secondary files
¹ Only full procedural files
¹ A combination of one primary file, optional secondary files, and one or more full
procedural files in which some of the input is controlled by the cycle, and other
input is controlled by the program.
¹ No files (for example, input can come from a parameter list or a data area data
structure).
Note: No cycle code is generated for a module when NOMAIN is specified on the
control specification.
General RPG IV Program Cycle
Figure 5 on page 20 shows the specific steps in the general flow of the RPG IV
program cycle. A program cycle begins with step 1 and continues through step 7,
then begins again with step 1.
The first and last time a program goes through the RPG IV cycle differ somewhat
from the normal cycle. Before the first record is read the first time through the
cycle, the program resolves any parameters passed to it, writes the records conditioned by the 1P (first page) indicator, does file and data initialization, and processes any heading or detail output operations having no conditioning indicators or
all negative conditioning indicators. For example, heading lines printed before the
first record is read might consist of constant or page heading information or fields
for reserved words, such as PAGE and *DATE. In addition, the program bypasses
total calculations and total output steps on the first cycle.
During the last time a program goes through the cycle, when no more records are
available, the LR (last record) indicator and L1 through L9 (control level) indicators
are set on, and file and data area cleanup is done.
 Copyright IBM Corp. 1994, 1999
19
Detailed RPG IV Program Cycle
Write
heading and
detail lines
Start
Perform
detail
calculations
Perform
total
calculations
Get input
record
No
Move fields
LR on
Write
total
output
Yes
End of
program
Figure 5. RPG IV Program Logic Cycle
.1/
All heading and detail lines (H or D in position 17 of the output specifications) are processed.
.2/
The next input record is read and the record identifying and control level
indicators are set on.
.3/
Total calculations are processed. They are conditioned by an L1 through
L9 or LR indicator, or an L0 entry.
.4/
All total output lines are processed. (identified by a T in position 17 of
the output specifications).
.5/
It is determined if the LR indicator is on. If it is on, the program is
ended.
.6/
The fields of the selected input records are moved from the record to a
processing area. Field indicators are set on.
.7/
All detail calculations are processed (those not conditioned by control
level indicators in positions 7 and 8 of the calculation specifications) on
the data from the record read at the beginning of the cycle.
Detailed RPG IV Program Cycle
In “General RPG IV Program Cycle” on page 19, the basic RPG IV Logic Cycle
was introduced. The following figures provide a detailed explanation of the RPG IV
Logic Cycle.
20
ILE RPG for AS/400 Reference
Detailed RPG IV Program Cycle
Start
Set of record identifying and
L1 through L9 indicators
Set of RT indicator
Parameters resolved
Yes
LR
on
First
time program
called
No
Yes
RT
on
Move result field
to factor 1 for
*ENTRY PLIST
*INIT
Perform program initialization:
Run program initialization
Perform data structure and
subfield initialization
Retrieve external indicators
(U1 through U8) and user
date fields
Open files
Load data area data
structures, arrays, and tables
Move result field to factor 1
for *ENTRY PLIST
Run initialization subroutine,
*INZSR, if specified
Store data structures and
variables for RESET operation
Perform heading and detail
output
Perform fetch overflow lines
Set off first page
indicators (1P)
No
Return to caller
No
Primary file
29
Yes
*GETIN
No
No
End of file
Undefined
record type or sequence error
Issue message
to requester
RPG exception/error
handling routine
Yes
Yes
Yes
Issue dump
FORCE
issued
Initialize to process
the forced file
24
Match fields
routine
24
No
No
Match fields
specified
No
36
Yes
No
Response
cancel
Cancel
with dump
Determine record
type and sequence
Yes
Yes
No
Move factor 2 to
result field for
*ENTRY PLIST
On first cycle, retrieve first
record from primary file and
and from each secondary
file in program
On other cycles, retrieve
input record from last file
processed, if required
*DETL
Set off
halt
indicator
29
No
Yes
Any
H1 through H9
indicators
on
Set on
L1 through L9
24
Yes
Note:
= RPG routine
(for detailed information
see the descriptions that
follow this picture).
Figure 6 (Part 1 of 2). Detailed RPG IV Object Program Cycle
Chapter 3. Program Cycle
21
Detailed RPG IV Program Cycle
Should
LR indicator
be set on
Yes
Set on LR indicator
and all control level
indicators
(L1 through L9)
Overflow
indicator
*OFL
Overflow
routine
Yes
Look-ahead
routine
No
No
Set on record identifying
indicator for record selected
Control break
Yes
Set MR indicator
on or off
No
Make data available
from last record read
Set field indicators
on or off
Yes
Set on appropriate
control level indicators
(L1 through L9)
Save control fields
Look-ahead
fields specified
Should
totals be
executed
No
No
*DETC
Perform detail calculations
Yes
*TOTC
Perform total calculations
4
*TOTL
Perform total output
LR
on ?
RETURN
Yes
Halt indicators
Yes
No
No
LR
on ?
No
*TERM
Yes
Write locked data
area structures
Reset external
indicators
*CANCL
Close files
Unlock other Data
areas locked by
the program
Halt
Indicators
No
Move factor
2 to parms
Note:
= RPG routine (for detailed
information, see the descriptions
that follow this figure).
Set return code.If
abnormal termination,
issue escape message
Return
to caller
Figure 6 (Part 2 of 2). Detailed RPG IV Object Program Cycle
22
ILE RPG for AS/400 Reference
Yes
Detailed RPG IV Program Cycle
Detailed RPG IV Object Program Cycle
Figure 6 on page 21 shows the specific steps in the detailed flow of the RPG IV
program cycle. The item numbers in the following description refer to the numbers
in the figure. Routines are flowcharted in Figure 9 on page 31 and in Figure 7 on
page 27.
.1/
The RT indicator is set off. If *ENTRY PLIST is specified the parameters
are resolved.
.2/
RPG IV checks for the first invocation of the program. If it is the first
invocation, program initialization continues. If not, it moves the result
field to factor 1 in the PARM statements in *ENTRY PLIST and
branches to step 5.
.3/
The program is initialized at *INIT in the cycle. This process includes:
performing data structure and subfield initialization, setting user date
fields; opening files; loading all data area data structures, arrays and
tables; moving the result field to factor 1 in the PARM statements in
*ENTRY PLIST; running the initialization subroutine *INZSR; and storing
the structures and variables for the RESET operation. Files are opened
in reverse order of their specification on the File Description Specifications.
.4/
Heading and detail lines (identified by an H or D in position 17 of the
output specifications) are written before the first record is read. Heading
and detail lines are always processed at the same time. If conditioning
indicators are specified, the proper indicator setting must be satisfied. If
fetch overflow logic is specified and the overflow indicator is on, the
appropriate overflow lines are written. File translation, if specified, is
done for heading and detail lines and overflow output. This step is the
return point in the program if factor 2 of an ENDSR operation contains
the value *DETL.
.5/
The halt indicators (H1 through H9) are tested. If all the halt indicators
are off, the program branches to step 8. Halt indicators can be set on
anytime during the program. This step is the return point in the program
if factor 2 of an ENDSR operation contains the value *GETIN.
a.
If any halt indicators are on, a message is issued to the user.
b.
If the response is to continue, the halt indicator is set off, and
the program returns to step 5. If the response is to cancel,
the program goes to step 6.
.6/
If the response is to cancel with a dump, the program goes to step 7;
otherwise, the program branches to step 36.
.7/
The program issues a dump and branches to step 36 (abnormal
ending).
.8/
All record identifying, 1P (first page), and control level (L1 through L9)
indicators are set off. All overflow indicators (OA through OG, OV) are
set off unless they have been set on during preceding detail calculations
or detail output. Any other indicators that are on remain on.
.9/
If the LR (last record) indicator is on, the program continues with step
10. If it is not on, the program branches to step 11.
Chapter 3. Program Cycle
23
Detailed RPG IV Program Cycle
24
.10/
The appropriate control level (L1 through L9) indicators are set on and
the program branches to step 29.
.11/
If the RT indicator is on, the program continues with step 12; otherwise,
the program branches to step 14.
.12/
Factor 2 is moved to the result field for the parameters of the *ENTRY
PLIST.
.13/
If the RT indicator is on (return code set to 0), the program returns to
the caller.
.14/
If a primary file is present in the program, the program continues with
step 15; otherwise, the program branches to step 29.
.15/
During the first program cycle, the first record from the primary file and
from each secondary file in the program is read. File translation is done
on the input records. In other program cycles, a record is read from the
last file processed. If this file is processed by a record address file, the
data in the record address file defines the record to be retrieved. If
lookahead fields are specified in the last record processed, the record
may already be in storage; therefore, no read may be done at this time.
.16/
If end of file has occurred on the file just read, the program branches to
step 20. Otherwise, the program continues with step 17.
.17/
If a record has been read from the file, the record type and record
sequence (positions 17 through 20 of the input specifications) are determined.
.18/
It is determined whether the record type is defined in the program, and if
the record sequence is correct. If the record type is undefined or the
record sequence is incorrect, the program continues with step 19; otherwise, the program branches to step 20.
.19/
The RPG IV exception/error handling routine receives control.
.20/
It is determined whether a FORCE operation was processed on the previous cycle. If a FORCE operation was processed, the program selects
that file for processing (step 21) and branches around the processing for
match fields (steps 22 and 23). The branch is processed because all
records processed with a FORCE operation are processed with the
matching record (MR) indicator off.
.21/
If FORCE was issued on the previous cycle, the program selects the
forced file for processing after saving any match fields from the file just
read. If the file forced is at end of file, normal primary/secondary multifile
logic selects the next record for processing and the program branches to
step 24.
.22/
If match fields are specified, the program continues with step 23; otherwise, the program branches to step 24.
.23/
The match fields routine receives control. (For detailed information on
the match fields routine, see “Match Fields Routine” on page 27.)
.24/
The LR (last record) indicator is set on when all records are processed
from the files that have an E specified in position 19 of the file
description specifications and all matching secondary records have been
processed. If the LR indicator is not set on, processing continues with
step 26.
ILE RPG for AS/400 Reference
Detailed RPG IV Program Cycle
.25/
The LR (last record) indicator is set on and all control level (L1 through
L9) indicators, and processing continues with step 29.
.26/
The record identifying indicator is set on for the record selected for processing.
.27/
It is determined whether the record selected for processing caused a
control break. A control break occurs when the value in the control fields
of the record being processed differs from the value of the control fields
of the last record processed. If a control break has not occurred, the
program branches to step 29.
.28/
When a control break occurs, the appropriate control level indicator (L1
through L9) is set on. All lower level control indicators are set on. The
program saves the contents of the control fields for the next comparison.
.29/
It is determined whether the total-time calculations and total-time output
should be done. Totals are always processed when the LR indicator is
on. If no control level is specified on the input specifications, totals are
bypassed on the first cycle and after the first cycle, totals are processed
on every cycle. If control levels are specified on the input specifications,
totals are bypassed until after the first record containing control fields
has been processed.
.30/
All total calculations conditioned by a control level entry (positions 7 and
8 of the calculation specifications). are processed. This step is the return
point in the program if factor 2 of an ENDSR operation contains the
value *TOTC.
.31/
All total output is processed. If fetch overflow logic is specified and the
overflow indicator (OA through OG, OV) associated with the file is on,
the overflow lines are written. File translation, if specified, is done for all
total output and overflow lines. This step is the return point in the
program if factor 2 of an ENDSR operation contains the value *TOTL.
.32/
If LR is on, the program continues with step 33; otherwise, the program
branches to step 41.
.33/
The halt indicators (H1 through H9) are tested. If any halt indicators are
on, the program branches to step 36 (abnormal ending). If the halt indicators are off, the program continues with step 34. If the RETURN operation code is used in calculations, the program branches to step 33 after
processing of that operation.
.34/
If LR is on, the program continues with step 35. If it is not on, the
program branches to step 38.
.35/
RPG IV program writes all arrays or tables for which the TOFILE
keyword has been specified on the definition specification and writes all
locked data area data structures. Output arrays and tables are translated, if necessary.
.36/
All open files are closed. The RPG IV program also unlocks all data
areas that have been locked but not unlocked by the program. If factor 2
of an ENDSR operation contains the value *CANCL, this step is the
return point.
.37/
The halt indicators (H1 through H9) are tested. If any halt indicators are
on, the program branches to step 39 (abnormal ending). If the halt indicators are off, the program continues with step 38.
Chapter 3. Program Cycle
25
Detailed RPG IV Program Cycle
.38/
The factor 2 fields are moved to the result fields on the PARMs of the
*ENTRY PLIST.
.39/
The return code is set. 1 = LR on, 2 = error, 3 = halt.
.40/
Control is returned to the caller.
Note: Steps 32 through 40 constitute the normal ending routine. For an abnormal
ending, steps 34 through 35 are bypassed.
.41/
It is determined whether any overflow indicators (OA through OG OV)
are on. If an overflow indicator is on, the program continues with step
42; otherwise, the program branches to step 43.
.42/
The overflow routine receives control. (For detailed information on the
overflow routine, see “Overflow Routine” on page 28.) This step is the
return point in the program if factor 2 of an ENDSR operation contains
the value *OFL.
.43/
The MR indicator is set on and remains on for the complete cycle that
processes the matching record if this is a multifile program and if the
record to be processed is a matching record. Otherwise, the MR indicator is set off.
.44/
Data from the last record read is made available for processing. Field
indicators are set on, if specified.
.45/
If lookahead fields are specified, the program continues with step 46;
otherwise, the program branches to step 47.
.46/
The lookahead routine receives control. (For detailed information on the
lookahead routine, see “Lookahead Routine” on page 29.)
.47/
Detail calculations are processed. This step is the return point in the
program if factor 2 of an ENDSR operation contains the value *DETC.
The program branches to step 4.
Initialization Subroutine
Refer to Figure 6 on page 21 to see a detailed explanation of the RPG IV initialization subroutine.
The initialization subroutine allows you to process calculation specifications before
1P output. A specific subroutine that is to be run at program initialization time can
be defined by specifying *INZSR in factor 1 of the subroutine's BEGSR operation.
Only one subroutine can be defined as an initialization subroutine. It is called at the
end of the program initialization step of the program cycle (that is, after data structures and subfields are initialized, external indicators and user data fields are
retrieved, files are opened, data area data structures, arrays, and tables are loaded,
and PARM result fields moved to factor 1 for *ENTRY PLIST). *INZSR may not be
specified as a file/program error/exception subroutine.
If a program ends with LR off, the initialization subroutine does not automatically
run during the next invocation of that program because the subroutine is part of the
initialization step of the program. However, if the initialization subroutine does not
complete before an exit is made from the program with LR off, the initialization subroutine will be re-run at the next invocation of that program.
The initialization subroutine is like any other subroutine in the program, other than
being called at program initialization time. It may be called using the EXSR or
26
ILE RPG for AS/400 Reference
Detailed RPG IV Program Cycle
CASxx operations, and it may call other subroutines or other programs. Any operation that is valid in a subroutine is valid in the initialization subroutine, with the
exception of the RESET operation. This is because the value used to reset a variable is not defined until after the initialization subroutine is run.
Any changes made to a variable during the initialization subroutine affect the value
that the variable is set to on a subsequent RESET operation. Default values can be
defined for fields in record formats by, for example, setting them in the initialization
subroutine and then using RESET against the record format whenever the default
values are to be used. The initialization subroutine can also retrieve information
such as the current time for 1P output.
There is no *INZSR associated with subprocedures. If a subprocedure is the first
procedure called in a module, the *INZSR of the main procedure will not be run,
although other initialization of global data will be done. The *INZSR of the main
procedure will be run when the main procedure is called.
Match fields
routine
Multifile
processing
No
Overflow
routine
Look-ahead
routine
Yes
Line
put out
with previous
fetch
Determine the
file to be processed
Yes
Retrive next
record for
this file
No
Match fields
sequence error
Yes
RPG exeption/
error handling
routine
Perform
overflow
output
Extract the
look-ahead
fields
Return
Return
No
Move the match
fields to the
match field hold area
Return
Figure 7. Detail Flow of RPG IV Match Fields, Overflow, and Lookahead Routines
Match Fields Routine
Figure 7 shows the specific steps in the RPG IV match fields routine. The item
numbers in the following descriptions refer to the numbers in the figure.
.1/
If multifile processing is being used, processing continues with step 2;
otherwise, the program branches to step 3.
.2/
The value of the match fields in the hold area is tested to determine
which file is to be processed next.
.3/
The RPG IV program extracts the match fields from the match files and
processes sequence checking. If the match fields are in sequence, the
program branches to step 5.
Chapter 3. Program Cycle
27
Detailed RPG IV Program Cycle
.4/
If the match fields are not in sequence, the RPG IV exception/error handling routine receives control.
.5/
The match fields are moved to the hold area for that file. A hold area is
provided for each file that has match fields. The next record is selected
for processing based on the value in the match fields.
Overflow Routine
Figure 7 on page 27 shows the specific steps in the RPG IV overflow routine. The
item numbers in the following descriptions refer to the numbers in the figure.
.1/
The RPG IV program determines whether the overflow lines were written
previously using the fetch overflow logic (step 30 in Figure 6 on
page 21). If the overflow lines were written previously, the program
branches to the specified return point; otherwise, processing continues
with step 2.
.2/
All output lines conditioned with an overflow indicator are tested and
written to the conditioned overflow lines.
The fetch overflow routine allows you to alter the basic RPG IV overflow logic to
prevent printing over the perforation and to let you use as much of the page as
possible. During the regular program cycle, the RPG IV program checks only once,
immediately after total output, to see if the overflow indicator is on. When the fetch
overflow function is specified, the RPG IV program checks overflow on each line for
which fetch overflow is specified.
Specify fetch overflow with an F in position 18 of the output specifications on any
detail, total, or exception lines for a PRINTER file. The fetch overflow routine does
not automatically cause forms to advance to the next page.
During output, the conditioning indicators on an output line are tested to determine
whether the line is to be written. If the line is to be written and an F is specified in
position 18, the RPG IV program tests to determine whether the overflow indicator
is on. If the overflow indicator is on, the overflow routine is fetched and the following operations occur:
¹ Only the overflow lines for the file with the fetch specified are checked for
output.
¹ All total lines conditioned by the overflow indicator are written.
¹ Forms advance to a new page when a skip to a line number less than the line
number the printer is currently on is specified in a line conditioned by an overflow indicator.
¹ Heading, detail, and exception lines conditioned by the overflow indicator are
written.
¹ The line that fetched the overflow routine is written.
¹ Any detail and total lines left to be written for that program cycle are written.
Position 18 of each OR line must contain an F if the overflow routine is to be used
for each record in the OR relationship. Fetch overflow cannot be used if an overflow indicator is specified in positions 21 through 29 of the same specification line.
If this occurs, the overflow routine is not fetched.
28
ILE RPG for AS/400 Reference
Detailed RPG IV Program Cycle
Use the fetch overflow routine when there is not enough space left on the page to
print the remaining detail, total, exception, and heading lines conditioned by the
overflow indicator. To determine when to fetch the overflow routine, study all possible overflow situations. By counting lines and spaces, you can calculate what
happens if overflow occurs on each detail, total, and exception line.
Lookahead Routine
Figure 7 on page 27 shows the specific steps in the RPG IV lookahead routine.
The item numbers in the following descriptions refer to the numbers in the figure.
.1/
The next record for the file being processed is read. However, if the file
is a combined or update file (identified by a C or U, respectively, in position 17 of the file description specifications), the lookahead fields from
the current record being processed is extracted.
.2/
The lookahead fields are extracted.
Ending a Program without a Primary File
If your program does not contain a primary file, you must specify a way for the
program to end:
¹ By setting the LR indicator on
¹ By setting the RT indicator on
¹ By setting an H1 through H9 indicator on
¹ By specifying the RETURN operation code
The LR, RT, H1 through H9 indicators, and the RETURN operation code, can be
used in conjunction with each other.
Program Control of File Processing
Specify a full procedural file (F in position 18 of the file description specifications) to
control all or partial input of a program. A full procedural file indicates that input is
controlled by program-specified calculation operations (for example, READ,
CHAIN). When both full procedural files and a primary file (P in position 18 of the
file description specifications) are specified in a program, some of the input is controlled by the program, and other input is controlled by the cycle. The program
cycle exists when a full procedural file is specified; however, file processing occurs
at detail or total calculation time for the full procedural file.
The file operation codes can be used for program control of input. These file operation codes are discussed in Chapter 22, “Operation Codes” on page 427.
Chapter 3. Program Cycle
29
Detailed RPG IV Program Cycle
START
Performs detail
calculations. Sets
resulting indicators.
Performs heading
operations. Performs
detail output operations.
If overflow line has been
reached, sets on overflow
indicator.
Moves data from record selected at
beginning of cycle into processing area.
Sets off control level
indicators. Sets off record
identifying indicators.
Overflow indicator on? Yes, performs
overflow operations.
Reads a record.
End-of-file? Yes, sets on
control level and LR indicators
and skips to perform total
calculations.
LR indicator on? Yes, end of
program has been reached.
Sets on record identifying indicators
for the record just read.
Performs total output operations.
If overflow line has been reached,
sets on overflow indicator.
Change in control fields?
Yes, sets on control level
indicators.
Performs total calculations.
Sets resulting indicators.
Figure 8. Programmer Control of Input Operation within the Program-Cycle
30
ILE RPG for AS/400 Reference
Note: The boxed steps
are bypassed when no
primary file exists;
that is, when the
programmer controls
all the input operations.
Detailed RPG IV Program Cycle
Exception/Error?
No
Process next
sequential instruction
Yes
Set on indicator and
process next
sequential instruction
Yes
Control passes to INFSR
or *PSSR subroutine
Yes
Set up file information
or program status data
structure if coded
Error indicator
coded on operation?
No
INFSR or *PSSR
subroutine present?
Return point specified?
No
No
Yes
Return to specified point
Status code
1121-1126
present ?
Yes
Resume current
operation
No
Exception is
Function Check
No
Percolate exception to
caller of this procedure
See text for more
information on the next point
in this procedure.
Yes
Issue message
to requester
No
Response cancel ?
Continue procedure
Yes
Cancel with Dump
No
Yes
Issue Dump
Close Files
Unlock Data Areas
Set procedure so
that it can be called again
Set return code and
percolate Function Check
Figure 9. Detail Flow of RPG IV Exception/Error Handling Routine
Chapter 3. Program Cycle
31
Detailed RPG IV Program Cycle
RPG IV Exception/Error Handling Routine
Figure 9 on page 31 shows the specific steps in the RPG IV exception/error handling routine. The item numbers in the following description refer to the numbers in
the figure.
32
.1/
Set up the file information or procedure status data structure, if specified, with status information.
.2/
If the exception/error occurred on an operation code that has an indicator specified in positions 73 and 74, the indicator is set on, and control
returns to the next sequential instruction in the calculations.
.3/
If the appropriate exception/error subroutine (INFSR or *PSSR) is
present in the procedure, the procedure branches to step 13; otherwise,
the procedure continues with step 4.
.4/
If the Status code is 1121-1126 (see “File Status Codes” on page 77),
control returns to the current instruction in the calculations. If not, the
procedure continues with step 5.
.5/
If the exception is a function check, the procedure continues with step 6.
If not, it branches to step 15.
.6/
An inquiry message is issued to the requester. For an interactive job,
the message goes to the requester. For a batch job, the message goes
to QSYSOPR. If QSYSOPR is not in break mode, a default response is
issued.
.7/
If the user's response is to cancel the procedure, the procedure continues with step 8. If not, the procedure continues.
.8/
If the user's response is to cancel with a dump, the procedure continues
with step 9. If not, the procedure branches to step 10.
.9/
A dump is issued.
.10/
All files are closed and data areas are unlocked
.11/
The procedure is set so that it can be called again.
.12/
The return code is set and the function check is percolated.
.13/
Control passes to the exception/error subroutine (INFSR or *PSSR).
.14/
If a return point is specified in factor 2 of the ENDSR operation for the
exception/error subroutine, the procedure goes to the specified return
point. If a return point is not specified, the procedure goes to step 4. If
a field name is specified in factor 2 of the ENDSR operation and the
content is not one of the RPG IV-defined return points (such as *GETIN
or *DETC), the procedure goes to step 6. No error is indicated, and the
original error is handled as though the factor 2 entry were blank.
.15/
If no invocation handles the exception, then it is promoted to function
check and the procedure branches to step 5. Otherwise, depending on
the action taken by the handler, control resumes in this procedure either
at step 10 or at the next machine instruction after the point at which the
exception occurred.
ILE RPG for AS/400 Reference
Indicators Defined on RPG IV Specifications
Chapter 4. RPG IV Indicators
An indicator is a one byte character field which contains either '1' (on) or '0' (off). It
is generally used to indicate the result of an operation or to condition (control) the
processing of an operation.
The indicator format can be specified on the definition specifications to define indicator variables. For a description of how to define character data in the indicator
format, see “Character Format” on page 162 and “Position 40 (Internal Data Type)”
on page 278. This chapter describes a special set of predefined RPG IV indicators
(*INxx).
RPG IV indicators are defined either by an entry on a specification or by the RPG
IV program itself. The positions on the specification in which you define the indicator determine how the indicator is used. An indicator that has been defined can
then be used to condition calculation and output operations.
The RPG IV program sets and resets certain indicators at specific times during the
program cycle. In addition, the state of most indicators can be changed by calculation operations. All indicators except MR, 1P, KA through KN, and KP through KY
can be set on with the SETON operation code; all indicators except MR and 1P can
be set off with the SETOFF operation code.
This chapter is divided into the following topics:
¹ Indicators defined on the RPG IV specifications
¹ Indicators not defined on the RPG IV specifications
¹ Using indicators
¹ Indicators referred to as data.
Indicators Defined on RPG IV Specifications
You can specify the following indicators on the RPG IV specifications:
¹ Overflow indicator (the OFLIND keyword on the file description specifications).
¹ Record identifying indicator (positions 21 and 22 of the input specifications).
¹ Control level indicator (positions 63 and 64 of the input specifications).
¹ Field indicator (positions 69 through 74 of the input specifications).
¹ Resulting indicator (positions 71 through 76 of the calculation specifications).
¹ *IN array, *IN(xx) array element or *INxx field (See “Indicators Referred to As
Data” on page 59 for a description of how an indicator is defined when used
with one of these reserved words.).
The defined indicator can then be used to condition operations in the program.
 Copyright IBM Corp. 1994, 1999
33
Indicators Defined on RPG IV Specifications
Overflow Indicators
An overflow indicator is defined by the OFLIND keyword on the file description
specifications. It is set on when the last line on a page has been printed or passed.
Valid indicators are *INOA through *INOG, *INOV, and *IN01 through *IN99. A
defined overflow indicator can then be used to condition calculation and output
operations. A description of the overflow indicator and fetch overflow logic is given
in “Overflow Routine” on page 28.
Record Identifying Indicators
A record identifying indicator is defined by an entry in positions 21 and 22 of the
input specifications and is set on when the corresponding record type is selected
for processing. That indicator can then be used to condition certain calculation and
output operations. Record identifying indicators do not have to be assigned in any
particular order.
The valid record identifying indicators are:
¹ 01-99
¹ H1-H9
¹ L1-L9
¹ LR
¹ U1-U8
¹ RT
For an externally described file, a record identifying indicator is optional, but, if you
specify it, it follows the same rules as for a program described file.
Generally, the indicators 01 through 99 are used as record identifying indicators.
However, the control level indicators (L1 through L9) and the last record indicator
(LR) can be used. If L1 through L9 are specified as record identifying indicators,
lower level indicators are not set on.
When you select a record type for processing, the corresponding record identifying
indicator is set on. All other record identifying indicators are off except when a file
operation code is used at detail and total calculation time to retrieve records from a
file (see below). The record identifying indicator is set on after the record is
selected, but before the input fields are moved to the input area. The record identifying indicator for the new record is on during total time for the old record; therefore, calculations processed at total time using the fields of the old record cannot
be conditioned by the record identifying indicator of the old record. You can set the
indicators off at any time in the program cycle; they are set off before the next
primary or secondary record is selected.
If you use a file operation code on the calculation specifications to retrieve a record,
the record identifying indicator is set on as soon as the record is retrieved from the
file. The record identifying indicator is not set off until the appropriate point in the
RPG IV cycle. (See Figure 8 on page 30.) Therefore, it is possible to have several
record identifying indicators for the same file, as well as record-not-found indicators,
set on concurrently if several operations are issued to the same file within the same
RPG IV program cycle.
34
ILE RPG for AS/400 Reference
Indicators Defined on RPG IV Specifications
Rules for Assigning Record Identifying Indicators
When you assign record identifying indicators to records in a program described
file, remember the following:
¹ You can assign the same indicator to two or more different record types if the
same operation is to be processed on all record types. To do this, you specify
the record identifying indicator in positions 21 and 22, and specify the record
identification codes for the various record types in an OR relationship.
¹ You can associate a record identifying indicator with an AND relationship, but it
must appear on the first line of the group. Record identifying indicators cannot
be specified on AND lines.
¹ An undefined record (a record in a program described file that was not
described by a record identification code in positions 23 through 46) causes the
program to halt.
¹ A record identifying indicator can be specified as a record identifying indicator
for another record type, as a field indicator, or as a resulting indicator. No diagnostic message is issued, but this use of indicators may cause erroneous
results.
When you assign record identifying indicators to records in an externally described
file, remember the following:
¹ AND/OR relationships cannot be used with record format names; however, the
same record identifying indicator can be assigned to more than one record.
¹ The record format name, rather than the file name, must be specified in positions 7 through 16.
For an example of record identifying indicators, see Figure 10 on page 36.
Chapter 4. RPG IV Indicators
35
Indicators Defined on RPG IV Specifications
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................
I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr....
*
I*Record identifying indicator 01 is set on if the record read
I*contains an S in position 1 or an A in position 1.
IINPUT1
NS 01
1 CS
I
OR
1 CA
I
1
25 FLD1
* Record identifying indicator 02 is set on if the record read
* contains XYZA in positions 1 through 4.
I
NS 02
1 CX
2 CY
3 CZ
I
AND
4 CA
I
1
15 FLDA
I
16
20 FLDB
* Record identifying indicator 95 is set on if any record read
* does not meet the requirements for record identifying indicators
* 01 or 02.
I
NS 95
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
IRcdname+++....Ri........................................................
*
* For an externally described file, record identifying indicator 10
* is set on if the ITMREC record is read and record identifying
* indicator 20 is set on if the SLSREC or COMREC records are read.
IITMREC
10
ISLSREC
20
ICOMREC
20
Figure 10. Examples of Record Identifying Indicators
Control Level Indicators (L1-L9)
A control level indicator is defined by an entry in positions 63 and 64 of the input
specifications, designating an input field as a control field. It can then be used to
condition calculation and output operations. The valid control level indicator entries
are L1 through L9.
A control level indicator designates an input field as a control field. When a control
field is read, the data in the control field is compared with the data in the same
control field from the previous record. If the data differs, a control break occurs, and
the control level indicator assigned to the control field is set on. You can then use
control level indicators to condition operations that are to be processed only when
all records with the same information in the control field have been read. Because
the indicators stay on for both total time and the first detail time, they can also be
used to condition total printing (last record of a control group) or detail printing (first
record in a control group). Control level indicators are set off before the next record
is read.
A control break can occur after the first record containing a control field is read.
The control fields in this record are compared to an area in storage that contains
hexadecimal zeros. Because fields from two different records are not being compared, total calculations and total output operations are bypassed for this cycle.
Control level indicators are ranked in order of importance with L1 being the lowest
and L9 the highest. All lower level indicators are set on when a higher level indicator is set on as the result of a control break. However, the lower level indicators
36
ILE RPG for AS/400 Reference
Indicators Defined on RPG IV Specifications
can be used in the program only if they have been defined. For example, if L8 is
set on by a control break, L1 through L7 are also set on. The LR (last record) indicator is set on when the input files are at end of file. LR is considered the highest
level indicator and forces L1 through L9 to be set on.
You can also define control level indicators as record identifying or resulting indicators. When you use them in this manner, the status of the lower level indicators is
not changed when a higher level indicator is set on. For example, if L3 is used as
a resulting indicator, the status of L2 and L1 would not change if L3 is set on.
The importance of a control field in relation to other fields determines how you
assign control level indicators. For example, data that demands a subtotal should
have a lower control level indicator than data that needs a final total. A control field
containing department numbers should have a higher control level indicator than a
control field containing employee numbers if employees are to be grouped within
departments (see Figure 11 on page 38).
Rules for Control Level Indicators
When you assign control level indicators, remember the following:
¹ You can specify control fields only for primary or secondary files.
¹ You cannot specify control fields for full procedural files; numeric input fields of
type binary, integer, unsigned or float; or look-ahead fields.
¹ You cannot use control level indicators when an array name is specified in
positions 49 through 62 of the input specifications; however, you can use
control level indicators with an array element. Control level indicators are not
allowed for null-capable fields.
¹ Control level compare operations are processed for records in the order in
which they are found, regardless of the file from which they come.
¹ If you use the same control level indicator in different record types or in different files, the control fields associated with that control level indicator must be
the same length (see Figure 11 on page 38) except for date, time, and
timestamp fields which need only match in type (that is, they can be different
formats).
¹ The control level indicator field length is the length of a control level indicator in
a record. For example, if L1 has a field length of 10 bytes in a record, the
control level indicator field length for L1 is 10 positions.
The control level indicator field length for split control fields is the sum of the
lengths of all fields associated with a control level indicator in a record. If L2
has a split control field consisting of 3 fields of length: 12 bytes, 2 bytes and 4
bytes; then the control level indicator field length for L2 is 18 positions.
If multiple records use the same control level indicator, then the control level
indicator field length is the length of only one record, not the sum of all the
lengths of the records.
Within a program, the sum of the control level indicator field lengths of all
control level indicators cannot exceed 256 positions.
¹ Record positions in control fields assigned different control level indicators can
overlap in the same record type (see Figure 12 on page 39). For record types
that require control or match fields, the total length of the control or match field
Chapter 4. RPG IV Indicators
37
Indicators Defined on RPG IV Specifications
must be less than or equal to 256. For example, in Figure 12 on page 39, 15
positions have been assigned to control levels.
¹ Field names are ignored in control level operations. Therefore, fields from different record types that have been assigned the same control level indicator
can have the same name.
¹ Control levels need not be written in any sequence. An L2 entry can appear
before L1. All lower level indicators need not be assigned.
¹ If different record types in a file do not have the same number of control fields,
unwanted control breaks can occur.
Figure 13 on page 39 shows an example of how to avoid unwanted control breaks.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
A* EMPLOYEE MASTER FILE -- EMPMSTL
A
R EMPREC
PFILE(EMPMSTL)
A
EMPLNO
6
A
DEPT
3
A
DIVSON
1
A*
A*
(ADDITIONAL FIELDS)
A*
A
R EMPTIM
PFILE(EMPMSTP)
A
EMPLNO
6
A
DEPT
3
A
DIVSON
1
A*
A*
(ADDITIONAL FIELDS)
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................
I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr....
*
* In this example, control level indicators are defined for three
* fields. The names of the control fields (DIVSON, DEPT, EMPLNO)
* give an indication of their relative importance.
* The division (DIVSON) is the most important group.
* It is given the highest control level indicator used (L3).
* The department (DEPT) ranks below the division;
* L2 is assigned to it. The employee field (EMPLNO) has
* the lowest control level indicator (L1) assigned to it.
*
IEMPREC
10
I
EMPLNO
L1
I
DIVSON
L3
I
DEPT
L2
*
* The same control level indicators can be used for different record
* types. However, the control fields having the same indicators must
* be the same length. For records in an externally described file,
* the field attributes are defined in the external description.
*
IEMPTIM
20
I
EMPLNO
L1
I
DEPT
L2
I
DIVSON
L3
Figure 11. Control Level Indicators (Two Record Types)
38
ILE RPG for AS/400 Reference
Indicators Defined on RPG IV Specifications
Control Field 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
Control Field 2
A total of 15 positions has been
assigned to these control levels.
Figure 12. Overlapping Control Fields
(L2)
(L2)
Salesman
Number
1
Salesman
Name
2
3
(L1)
Salesman
Number
15
1
Salesman Record
Item Number
2
3
Amount
5
6
8
Item Record
Figure 13 (Part 1 of 4). How to Avoid Unwanted Control Breaks
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................
I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr....
ISALES
01
I
1
2 L2FLD
L2
I
3
15 NAME
IITEM
02
I
1
2 L2FLD
L2
I
3
5 L1FLD
L1
I
6
8 AMT
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
* Indicator 11 is set on when the salesman record is read.
*
C
01
SETON
11
*
* Indicator 11 is set off when the item record is read.
* This allows the normal L1 control break to occur.
*
C
02
SETOFF
11
C
02AMT
ADD
L1TOT
L1TOT
5 0
CL1
L1TOT
ADD
L2TOT
L2TOT
5 0
CL2
L2TOT
ADD
LRTOT
LRTOT
5 0
*
Figure 13 (Part 2 of 4). How to Avoid Unwanted Control Breaks
Chapter 4. RPG IV Indicators
39
Indicators Defined on RPG IV Specifications
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
OFilename++DF..N01N02N03Excnam++++B++A++Sb+Sa+...........................
O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat
OPRINTER
D
01
1 1
O
L2FLD
5
O
NAME
25
O
D
02
1
O
L1FLD
15
O
AMT
Z
15
*
* When the next item record causes an L1 control break, no total
* output is printed if indicator 11 is on. Detail calculations
* are then processed for the item record.
*
OFilename++DF..N01N02N03Excnam++++B++A++Sb+Sa+...........................
O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat
O
T
L1N11
1
O
L1TOT
ZB
25
O
27 '*'
O
T
L2
1
O
L2TOT
ZB
25
O
28 '**'
O
T
LR
1
O
LRTOT
ZB
25
Figure 13 (Part 3 of 4). How to Avoid Unwanted Control Breaks
01
JOHN SMITH
3
2
5 *
4
4 *
9 **
100
100
101
02
*
JANE DOE
100
100
*
6
2
8 *
3
3 *
11 **
101
Unwanted
control
break
01
JOHN SMITH
100
100
101
Unwanted
control
break
02
JANE DOE
100
100
101
20
Output Showing Unwanted Control Level Break
3
2
5 *
4
4 *
9 **
6
2
8 *
3
3 *
11 **
20
Corrected Output
Figure 13 (Part 4 of 4). How to Avoid Unwanted Control Breaks
Different record types normally contain the same number of control fields.
However, some applications require a different number of control fields in some
records.
40
ILE RPG for AS/400 Reference
Indicators Defined on RPG IV Specifications
The salesman records contain only the L2 control field. The item records contain
both L1 and L2 control fields. With normal RPG IV coding, an unwanted control
break is created by the first item record following the salesman record. This is
recognized by an L1 control break immediately following the salesman record and
results in an asterisk being printed on the line below the salesman record.
¹ Numeric control fields are compared in zoned decimal format. Packed numeric
input fields lengths can be determined by the formula: d = 2n − 1Where d =
number of digits in the field and n = length of the input field. The number of
digits in a packed numeric field is always odd; therefore, when a packed
numeric field is compared with a zoned decimal numeric field, the zoned field
must have an odd length.
¹ When numeric control fields with decimal positions are compared to determine
whether a control break has occurred, they are always treated as if they had no
decimal positions. For instance, 3.46 is considered equal to 346.
¹ If you specify a field as numeric, only the positive numeric value determines
whether a control break has occurred; that is, a field is always considered to be
positive. For example, -5 is considered equal to +5.
¹ Date and time fields are converted to *ISO format before being compared
¹ Graphic data is compared by hexadecimal value
Split Control Field
A split control field is formed when you assign more than one field in an input
record the same control level indicator. For a program described file, the fields that
have the same control level indicator are combined by the program in the order
specified in the input specifications and treated as a single control field (see
Figure 14). The first field defined is placed in the high-order (leftmost) position of
the control field, and the last field defined is placed in the low-order (rightmost)
position of the control field.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................
I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr....
IMASTER
01
I
28
31 CUSNO
L4
I
15
20 ACCTNO
L4
I
50
52 REGNO
L4
Figure 14. Split Control Fields
For an externally described file, fields that have the same control level indicator are
combined in the order in which the fields are described in the data description
specifications (DDS), not in the order in which the fields are specified on the input
specifications. For example, if these fields are specified in DDS in the following
order:
¹ EMPNO
¹ DPTNO
¹ REGNO
and if these fields are specified with the same control level indicator in the following
order on the input specifications:
Chapter 4. RPG IV Indicators
41
Indicators Defined on RPG IV Specifications
¹ REGNO L3
¹ DPTNO L3
¹ EMPNO L3
the fields are combined in the following order to form a split control field: EMPNO
DPTNO REGNO.
Some special rules for split control fields are:
¹ For one control level indicator, you can split a field in some record types and
not in others if the field names are different. However, the length of the field,
whether split or not, must be the same in all record types.
¹ You can vary the length of the portions of a split control field for different record
types if the field names are different. However, the total length of the portions
must always be the same.
¹ A split control field can be made up of a combination of packed decimal fields
and zoned decimal fields so long as the field lengths (in digits or characters)
are the same.
¹ You must assign all portions of a split control field in one record type the same
field record relation indicator and it must be defined on consecutive specification lines.
¹ When a split control field contains a date, time, or timestamp field than all fields
in the split control field must be of the same type.
Figure 15 shows examples of the preceding rules.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................
I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr....
IDISK
BC 91
95 C1
I
OR
92
95 C2
I
OR
93
95 C3
I
* All portions of the split control field must be assigned the same
* control level indicator and all must have the same field record
* relation entry.
I
1
5 FLD1A
L1
I
46
50 FLD1B
L1
I
11
13 FLDA
L2
I
51
60 FLD2A
L3
I
31
40 FLD2B
L3
I
71
75 FLD3A
L4 92
I
26
27 FLD3B
L4 92
I
41
45 FLD3C
L4 92
I
61
70 FLDB
92
I
21
25 FLDC
92
I
6
10 FLD3D
L4 93
I
14
20 FLD3E
L4 93
Figure 15. Split Control Fields–Special Rules
The record identified by a '1' in position 95 has two split control fields:
1. FLD1A and FLD1B
2. FLD2A and FLD2B
42
ILE RPG for AS/400 Reference
Indicators Defined on RPG IV Specifications
The record identified with a '2' in position 95 has three split control fields:
1. FLD1A and FLD1B
2. FLD2A and FLD2B
3. FLD3A, FLD3B, and FLD3C
The third record type, identified by the 3 in position 95, also has three split control
fields:
1. FLD1A and FLD1B
2. FLD2A and FLD2B
3. FLD3D and FLD3E
Field Indicators
A field indicator is defined by an entry in positions 69 and 70, 71 and 72, or 73 and
74 of the input specifications. The valid field indicators are:
¹ 01-99
¹ H1-H9
¹ U1-U8
¹ RT
You can use a field indicator to determine if the specified field or array element is
greater than zero, less than zero, zero, or blank. Positions 69 through 72 are valid
for numeric fields only; positions 73 and 74 are valid for numeric or character fields.
An indicator specified in positions 69 and 70 is set on when the numeric input field
is greater than zero; an indicator specified in positions 71 and 72 is set on when
the numeric input field is less than zero; and an indicator specified in positions 73
and 74 is set on when the numeric input field is zero or when the character input
field is blank. You can then use the field indicator to condition calculation or output
operations.
A field indicator is set on when the data for the field or array element is extracted
from the record and the condition it represents is present in the input record. This
field indicator remains on until another record of the same type is read and the
condition it represents is not present in the input record, or until the indicator is set
off as the result of a calculation.
You can use halt indicators (H1 through H9) as field indicators to check for an error
condition in the field or array element as it is read into the program.
Rules for Assigning Field Indicators
When you assign field indicators, remember the following:
¹ Indicators for plus, minus, zero, or blank are set off at the beginning of the
program. They are not set on until the condition (plus, minus, zero, or blank) is
satisfied by the field being tested on the record just read.
¹ Field indicators cannot be used with entire arrays or with look-ahead fields.
However, an entry can be made for an array element. Field indicators are
allowed for null-capable fields only if ALWNULL(*USRCTL) is used.
Chapter 4. RPG IV Indicators
43
Indicators Defined on RPG IV Specifications
¹
A numeric input field can be assigned two or three field indicators. However,
only the indicator that signals the result of the test on that field is set on; the
others are set off.
¹ If the same field indicator is assigned to fields in different record types, its state
(on or off) is always based on the last record type selected.
¹ When different field indicators are assigned to fields in different record types, a
field indicator remains on until another record of that type is read. Similarly, a
field indicator assigned to more than one field within a single record type
always reflects the status of the last field defined.
¹ The same field indicator can be specified as a field indicator on another input
specification, as a resulting indicator, as a record identifying indicator, or as a
field record relation indicator. No diagnostic message is issued, but this use of
indicators could cause erroneous results, especially when match fields or level
control is involved.
¹ If the same indicator is specified in all three positions, the indicator is always
set on when the record containing this field is selected.
Resulting Indicators
A resulting indicator is defined by an entry in positions 71 through 76 of the calculation specifications. The purpose of the resulting indicators depends on the operation code specified in positions 26 through 35. (See the individual operation code in
Chapter 22, “Operation Codes” on page 427 for a description of the purpose of the
resulting indicators.) For example, resulting indicators can be used to test the result
field after an arithmetic operation, to identify a record-not-found condition, to indicate an exception/error condition for a file operation, or to indicate an end-of-file
condition.
The valid resulting indicators are:
¹ 01-99
¹ H1-H9
¹ OA-OG, OV
¹ L1-L9
¹ LR
¹ U1-U8
¹ KA-KN, KP-KY (valid only with SETOFF)
¹ RT
You can specify resulting indicators in three places (positions 71-72, 73-74, and
75-76) of the calculation specifications. The positions in which the resulting indicator is defined determine the condition to be tested.
In most cases, when a calculation is processed, the resulting indicators are set off,
and, if the condition specified by a resulting indicator is satisfied, that indicator is
set on. However, there some exceptions to this rule, notably “LOOKUP (Look Up a
Table or Array Element)” on page 559, “SETOFF (Set Indicator Off)” on page 654,
and “SETON (Set Indicator On)” on page 655. A resulting indicator can be used as
a conditioning indicator on the same calculation line or in other calculations or
output operations. When you use it on the same line, the prior setting of the indi-
44
ILE RPG for AS/400 Reference
Indicators Not Defined on the RPG IV Specifications
cator determines whether or not the calculation is processed. If it is processed, the
result field is tested and the current setting of the indicator is determined (see
Figure 16 on page 45).
Rules for Assigning Resulting Indicators
When assigning resulting indicators, remember the following:
¹ Resulting indicators cannot be used when the result field refers to an entire
array.
¹ If the same indicator is used to test the result of more than one operation, the
last operation processed determines the setting of the indicator.
¹ When L1 through L9 indicators are used as resulting indicators and are set on,
lower level indicators are not set on. For example, if L8 is set on, L1 through L7
are not set on.
¹ If H1 through H9 indicators are set on when used as resulting indicators, the
program halts unless the halt indicator is set off prior to being checked in the
program cycle. (See Chapter 3, “Program Cycle” on page 19).
¹ The same indicator can be used to test for more than one condition depending
on the operation specified.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
*
* Two resulting indicators are used to test for the different
* conditions in a subtraction operation. These indicators are
* used to condition the calculations that must be processed for
* a payroll job. Indicator 10 is set on if the hours worked (HRSWKD)
* are greater than 40 and is then used to condition all operations
* necessary to find overtime pay. If Indicator 20 is not on
* (the employee worked 40 or more hours), regular pay based on a
* 40-hour week is calculated.
*
C
HRSWKD
SUB
40
OVERTM
3 01020
*
C N20PAYRAT
MULT (H) 40
PAY
6 2
C
10OVERTM
MULT (H) OVRRAT
OVRPAY
6 2
C
10OVRPAY
ADD
PAY
PAY
*
* If indicator 20 is on (employee worked less than 40 hours), pay
* based on less than a 40-hour week is calculated.
C
20PAYRAT
MULT (H) HRSWKD
PAY
*
Figure 16. Resulting Indicators Used to Condition Operations
Indicators Not Defined on the RPG IV Specifications
Not all indicators that can be used as conditioning indicators in an RPG IV program
are defined on the specification forms. External indicators (U1 through U8) are
defined by a CL command or by a previous RPG IV program. Internal indicators
(1P, LR, MR, and RT) are defined by the RPG IV program cycle itself.
Chapter 4. RPG IV Indicators
45
Indicators Not Defined on the RPG IV Specifications
External Indicators
The external indicators are U1 through U8. These indicators can be set in a CL
program or in an RPG IV program. In a CL program, they can be set by the SWS
(switch-setting) parameter on the CL commands CHGJOB (Change Job) or
CRTJOBD (Create Job Description). In an RPG IV program, they can be set as a
resulting indicator or field indicator.
The status of the external indicators can be changed in the program by specifying
them as resulting indicators on the calculation specifications or as field indicators
on the input specifications. However, changing the status of the OS/400 job
switches with a CL program during processing of an RPG IV program has no effect
on the copy of the external indicators used by the RPG IV program. Setting the
external indicators on or off in the program has no effect on file operations. File
operations function according to the status of the U1 through U8 indicators when
the program is initialized. However, when a program ends normally with LR on, the
external indicators are copied back into storage, and their status reflects their last
status in the RPG IV program. The current status of the external indicators can
then be used by other programs.
Note: When using “RETURN (Return to Caller)” on page 637 with the LR indicator off, you are specifying a return without an end and, as a result, no
external indicators are updated.
Internal Indicators
Internal indicators include:
¹ First page indicator
¹ Last record indicator
¹ Matching record indicator
¹ Return Indicator.
First Page Indicator (1P)
The first page (1P) indicator is set on by the RPG IV program when the program
starts running and is set off by the RPG IV program after detail time output. The
first record will be processed after detail time output. The 1P indicator can be used
to condition heading or detail records that are to be written at 1P time. Do not use
the 1P indicator in any of the following ways:
¹ To condition output fields that require data from input records; this is because
the input data will not be available.
¹ To condition total or exception output lines
¹ In an AND relationship with control level indicators
¹ As a resulting indicator
¹ When NOMAIN is specified on a control specification
46
ILE RPG for AS/400 Reference
Indicators Not Defined on the RPG IV Specifications
Last Record Indicator (LR)
In a program that contains a primary file, the last record indicator (LR) is set on
after the last record from a primary/secondary file has been processed, or it can be
set on by the programmer.
The LR indicator can be used to condition calculation and output operations that
are to be done at the end of the program. When the LR indicator is set on, all other
control level indicators (L1 through L9) are also set on. If any of the indicators L1
through L9 have not been defined as control level indicators, as record identifying
indicators, as resulting indicators, or by *INxx, the indicators are set on when LR is
set on, but they cannot be used in other specifications.
In a program that does not contain a primary file, you can set the LR indicator on
as one method to end the program. (For more information on how to end a
program without a primary file, see Chapter 3, “Program Cycle” on page 19.) To
set the LR indicator on, you can specify the LR indicator as a record identifying
indicator or a resulting indicator. If LR is set on during detail calculations, all other
control level indicators are set on at the beginning of the next cycle. LR and the
record identifying indicators are both on throughout the remainder of the detail
cycle, but the record identifying indicators are set off before LR total time.
Matching Record Indicator (MR)
The matching record indicator (MR) is associated with the matching field entries M1
through M9. It can only be used in a program when Match Fields are defined in the
primary and at least one secondary file.
The MR indicator is set on when all the matching fields in a record of a secondary
file match all the matching fields of a record in the primary file. It remains on
during the complete processing of primary and secondary records. It is set off
when all total calculations, total output, and overflow for the records have been
processed.
At detail time, MR always indicates the matching status of the record just selected
for processing; at total time, it reflects the matching status of the previous record. If
all primary file records match all secondary file records, the MR indicator is always
on.
Use the MR indicator as a field record relation indicator, or as a conditioning indicator in the calculation specifications or output specifications to indicate operations
that are to be processed only when records match. The MR indicator cannot be
specified as a resulting indicator.
For more information on Match Fields and multi-file processing, see Chapter 7,
“General File Considerations” on page 99.
Return Indicator (RT)
You can use the return indicator (RT) to indicate to the internal RPG IV logic that
control should be returned to the calling program. The test to determine if RT is on
is made after the test for the status of LR and before the next record is read. If RT
is on, control returns to the calling program. RT is set off when the program is
called again.
Because the status of the RT indicator is checked after the halt indicators (H1
through H9) and LR indicator are tested, the status of the halt indicators or the LR
Chapter 4. RPG IV Indicators
47
Using Indicators
indicator takes precedence over the status of the RT indicator. If both a halt indicator and the RT indicator are on, the halt indicator takes precedence. If both the
LR indicator and RT indicator are on, the program ends normally.
RT can be set on as a record identifying indicator, a resulting indicator, or a field
indicator. It can then be used as a conditioning indicator for calculation or output
operations.
For a description of how RT can be used to return control to the calling program,
see the chapter on calling programs in the ILE RPG for AS/400 Programmer's
Guide.
Using Indicators
Indicators that you have defined as overflow indicators, control level indicators,
record identifying indicators, field indicators, resulting indicators, *IN, *IN(xx), *INxx,
or those that are defined by the RPG IV language can be used to condition files,
calculation operations, or output operations. An indicator must be defined before it
can be used as a conditioning indicator. The status (on or off) of an indicator is not
affected when it is used as a conditioning indicator. The status can be changed
only by defining the indicator to represent a certain condition.
Note: Indicators that control the cycle function solely as conditioning indicators
when used in a NOMAIN module; or in a subprocedure that is active, but
where the main procedure of the module is not. Indicators that control the
cycle include: LR, RT, H1-H9, and control level indicators.
File Conditioning
The file conditioning indicators are specified by the EXTIND keyword on the file
description specifications. Only the external indicators U1 through U8 are valid for
file conditioning. (The USROPN keyword can be used to specify that no implicit
OPEN should be done.)
If the external indicator specified is off when the program is called, the file is not
opened and no data transfer to or from the file will occur when the program is
running. Primary and secondary input files are processed as if they were at end-offile. The end-of-file indicator is set on for all READ operations to that file. Input,
calculation, and output specifications for the file need not be conditioned by the
external indicator.
Rules for File Conditioning
When you condition files, remember the following:
¹ A file conditioning entry can be made for input, output, update, or combined
files.
¹ A file conditioning entry cannot be made for table or array input.
¹ Output files for tables can be conditioned by U1 through U8. If the indicator is
off, the table is not written.
¹ A record address file can be conditioned by U1 through U8, but the file processed by the record address file cannot be conditioned by U1 through U8.
¹ If the indicator conditioning a primary file with matching records is off, the MR
indicator is not set on.
48
ILE RPG for AS/400 Reference
Using Indicators
¹ Input does not occur for an input, an update, or a combined file if the indicator
conditioning the file is off. Any indicators defined on the associated Input specifications in positions 63-74 will be processed as usual using the existing values
in the input fields.
¹ Data transfer to the file does not occur for an output, an update, or a combined
file if the indicator conditioning the file is off. Any conditioning indicators,
numeric editing, or blank after that are defined on the output specifications for
these files will be processed as usual.
¹ If the indicator conditioning an input, an update, or a combined file is off, the
file is considered to be at end of file. All defined resulting indicators are set off
at the beginning of each specified I/O operation. The end-of-file indicator is set
on for READ, READC, READE, READPE, and READP operations. CHAIN,
EXFMT, SETGT, SETLL, and UNLOCK operations are ignored and all defined
resulting indicators remain set off.
Field Record Relation Indicators
Field record relation indicators are specified in positions 67 and 68 of the input
specifications. The valid field record relation indicators are:
¹ 01-99
¹ H1-H9
¹ MR
¹ RT
¹ L1-L9
¹ U1-U8
Field record relation indicators cannot be specified for externally described files.
You use field record relation indicators to associate fields with a particular record
type when that record type is one of several in an OR relationship. The field
described on the specification line is available for input only if the indicator specified
in the field record relation entry is on or if the entry is blank. If the entry is blank,
the field is common to all record types defined by the OR relationship.
Assigning Field Record Relation Indicators
You can use a record identifying indicator (01 through 99) in positions 67 and 68 to
relate a field to a particular record type. When several record types are specified in
an OR relationship, all fields that do not have a field record relation indicator in
positions 67 and 68 are associated with all record types in the OR relationship. To
relate a field to just one record type, you enter the record identifying indicator
assigned to that record type in positions 67 and 68 (see Figure 17 on page 51).
An indicator (01 through 99) that is not a record identifying indicator can also be
used in positions 67 and 68 to condition movement of the field from the input area
to the input fields.
Control fields, which you define with an L1 through L9 indicator in positions 63 and
64 of the input specifications, and match fields, which are specified by a match
value (M1 through M9) in positions 65 and 66 of the input specifications, can also
be related to a particular record type in an OR relationship if a field record relation
indicator is specified. Control fields or match fields in the OR relationship that do
Chapter 4. RPG IV Indicators
49
Using Indicators
not have a field record relation indicator are used with all record types in the OR
relationship.
If two control fields have the same control level indicator or two match fields have
the same matching level value, a field record relation indicator can be assigned to
just one of the match fields. In this case, only the field with the field record relation
indicator is used when that indicator is on. If none of the field record relation indicators are on for that control field or match field, the field without a field record
relation indicator is used. Control fields and match fields can only have entries of
01 through 99 or H1 through H9 in positions 67 and 68.
You can use positions 67 and 68 to specify that the program accepts and uses
data from a particular field only when a certain condition occurs (for example, when
records match, when a control break occurs, or when an external indicator is on).
You can indicate the conditions under which the program accepts data from a field
by specifying indicators L1 through L9, MR, or U1 through U8 in positions 67 and
68. Data from the field named in positions 49 through 62 is accepted only when the
field record relation indicator is on.
External indicators are primarily used when file conditioning is specified with the
“EXTIND(*INUx)” on page 263 keyword on the file description specifications.
However, they can be used even though file conditioning is not specified.
A halt indicator (H1 through H9) in positions 67 and 68 relates a field to a record
that is in an OR relationship and also has a halt indicator specified in positions 21
and 22.
Remember the following points when you use field record relation indicators:
¹ Control level (positions 63 and 64) and matching fields (positions 65 and 66)
with the same field record relation indicator must be grouped together.
¹ Fields used for control level (positions 63 and 64) and matching field entries
(positions 65 and 66) without a field record relation indicator must appear
before those used with a field record relation indicator.
¹ Control level (positions 63 and 64) and matching fields (positions 65 and 66)
with a field record relation indicator (positions 67 and 68) take precedence,
when the indicator is on, over control level and matching fields of the same
level without an indicator.
¹ Field record relations (positions 67 and 68) for matching and control level fields
(positions 63 through 66) must be specified with record identifying indicators
(01 through 99 or H1 through H9) from the main specification line or an OR
relation line to which the matching field refers. If multiple record types are
specified in an OR relationship, an indicator that specifies the field relation can
be used to relate matching and control level fields to the pertinent record type.
¹ Noncontrol level (positions 63 and 64) and matching field (positions 65 and 66)
specifications can be interspersed with groups of field record relation entries
(positions 67 and 68).
¹ The MR indicator can be used as a field record relation indicator to reduce
processing time when certain fields of an input record are required only when a
matching condition exists.
50
ILE RPG for AS/400 Reference
Using Indicators
¹ The number of control levels (L1 through L9) specified for different record types
in the OR relationship can differ. There can be no control level for certain
record types and a number of control levels for other record types.
¹ If all matching fields (positions 65 and 66) are specified with field record relation
indicators (positions 67 and 68), each field record relation indicator must have a
complete set of matching fields associated with it.
¹ If one matching field is specified without a field record relation indicator, a complete set of matching fields must be specified for the fields without a field
record relation indicator.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................
I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr....
IREPORT
AA 14
1 C5
I
OR
16
1 C6
I
20
30 FLDB
I
2
10 FLDA
07
*
* Indicator 07 was specified elsewhere in the program.
*
I
40
50 FLDC
14
I
60
70 FLDD
16
Figure 17. Field Record Relation
The file contains two different types of records, one identified by a 5 in position 1
and the other by a 6 in position 1. The FLDC field is related by record identifying
indicator 14 to the record type identified by a 5 in position 1. The FLDD field is
related to the record type having a 6 in position 1 by record identifying indicator 16.
This means that FLDC is found on only one type of record (that identified by a 5 in
position 1) and FLDD is found only on the other type. FLDA is conditioned by indicator 07, which was previously defined elsewhere in the program. FLDB is found on
both record types because it is not related to any one type by a record identifying
indicator.
Function Key Indicators
You can use function key indicators in a program that contains a WORKSTN device
if the associated function keys are specified in data description specifications
(DDS). Function keys are specified in DDS with the CFxx or CAxx keyword. For an
example of using function key indicators with a WORKSTN file, see the WORKSTN
chapter in the ILE RPG for AS/400 Programmer's Guide.
Function Key
Indicator
Corresponding
Function Key
Function Key
Indicator
Corresponding
Function Key
KA
1
KM
13
KB
2
KN
14
KC
3
KP
15
KD
4
KQ
16
KE
5
KR
17
KF
6
KS
18
KG
7
KT
19
Chapter 4. RPG IV Indicators
51
Using Indicators
Function Key
Indicator
Corresponding
Function Key
Function Key
Indicator
Corresponding
Function Key
KH
8
KU
20
KI
9
KV
21
KJ
10
KW
22
KK
11
KX
23
KL
12
KY
24
The function key indicators correspond to function keys 1 through 24. Function key
indicator KA corresponds to function key 1, KB to function key 2 ... KY to function
key 24.
Function key indicators that are set on can then be used to condition calculation or
output operations. Function key indicators can be set off by the SETOFF operation.
Halt Indicators (H1-H9)
You can use the halt indicators (H1 through H9) to indicate errors that occur during
the running of a program. The halt indicators can be set on as record identifying
indicators, field indicators, or resulting indicators.
The halt indicators are tested at the *GETIN step of the RPG IV cycle (see
Chapter 3, “Program Cycle” on page 19). If a halt indicator is on, a message is
issued to the user. The following responses are valid:
¹ Set off the halt indicator and continue the program.
¹ Issue a dump and end the program.
¹ End the program with no dump.
If a halt indicator is on when a RETURN operation inside a main procedure is processed, or when the LR indicator is on, the called program ends abnormally. The
calling program is informed that the called program ended with a halt indicator on.
Note: If the keyword NOMAIN is specified on a control specification, then any halt
indicators are ignored except as conditioning indicators.
For a detailed description of the steps that occur when a halt indicator is on, see
the detailed flowchart of the RPG IV cycle in Chapter 3, “Program Cycle” on
page 19.
Indicators Conditioning Calculations
Indicators that are used to specify the conditions under which a calculation is done
are to be defined elsewhere in the program. Indicators to condition calculations can
be specified in positions 7 and 8 and/or in positions 9 through 11.
Positions 7 and 8
You can specify control level indicators (L1 through L9 and LR) in positions 7 and 8
of the calculation specifications.
If positions 7 and 8 are blank, the calculation is processed at detail time, is a statement within a subroutine, or is a declarative statement. If indicators L1 through L9
are specified, the calculation is processed at total time only when the specified indi-
52
ILE RPG for AS/400 Reference
Using Indicators
cator is on. If the LR indicator is specified, the calculation is processed during the
last total time.
Note: An L0 entry can be used to indicate that the calculation is a total calculation
that is to be processed on every program cycle.
Positions 9-11
You can use positions 9 through 11 of the calculation specifications to specify indicators that control the conditions under which an operation is processed. You can
specify N is position 9 to indicate that the indicator should be tested for the value of
off ('0') The valid entries for positions 10 through 11 are:
¹ 01-99
¹ H1-H9
¹ MR
¹ OA-OG, OV
¹ L1-L9
¹ LR
¹ U1-U8
¹ KA-KN, KP-KY
¹ RT
Any indicator that you use in positions 9 through 11 must be previously defined as
one of the following types of indicators:
¹ Overflow indicators (file description specifications “OFLIND(*INxx)” on page 266
¹ Record identifying indicators (input specifications, positions 21 and 22)
¹ Control level indicators (input specifications, positions 63 and 64)
¹ Field indicators (input specifications, positions 69 through 74)
¹ Resulting indicators (calculation specifications, positions 71 through 76)
¹ External indicators
¹ Indicators are set on, such as LR and MR
¹ *IN array, *IN(xx) array element, or *INxx field (see “Indicators Referred to As
Data” on page 59 for a description of how an indicator is defined when used
with one of these reserved words).
If the indicator must be off to condition the operation, place an N in positions 9. The
indicators in grouped AND/OR lines, plus the control level indicators (if specified in
positions 7 and 8), must all be exactly as specified before the operation is done as
in Figure 18 on page 54.
Chapter 4. RPG IV Indicators
53
Using Indicators
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
*
C
25
CAN L1
SUB
TOTAL
TOTAL
.A/
CL2 10
CANNL3TOTAL
MULT
05
SLSTAX
.B/
*
Figure 18. Conditioning Operations (Control Level Indicators)
Assume that indicator 25 represents a record type and that a control level 2 break
occurred when record type 25 was read. L1 and L2 are both on. All operations
conditioned by the control level indicators in positions 7 and 8 are done before
operations conditioned by control level indicators in positions 9 through 11. Therefore, the operation in .B/ occurs before the operation in .A/. The operation in .A/ is
done on the first record of the new control group indicated by 25, whereas the
operation in .B/ is a total operation done for all records of the previous control
group.
The operation in .B/ can be done when the L2 indicator is on provided the other
conditions are met: Indicator 10 must be on; the L3 indicator must not be on.
The operation conditioned by both L2 and NL3 is done only when a control level 2
break occurs. These two indicators are used together because this operation is not
to be done when a control level 3 break occurs, even though L2 is also on.
Some special considerations you should know when using conditioning indicators in
positions 9 through 11 are as follows:
¹ With externally described work station files, the conditioning indicators on the
calculation specifications must be either defined in the RPG program or be
defined in the DDS source for the workstation file.
¹ With program described workstation files, the indicators used for the workstation file are unknown at compile time of the RPG program. Thus indicators
01-99 are assumed to be declared and they can be used to condition the calculation specifications without defining them.
¹ Halt indicators can be used to end the program or to prevent the operation from
being processed when a specified error condition is found in the input data or
in another calculation. Using a halt indicator is necessary because the record
that causes the halt is completely processed before the program stops. Therefore, if the operation is processed on an error condition, the results are in error.
A halt indicator can also be used to condition an operation that is to be done
only when an error occurs.
¹ If LR is specified in positions 9 through 11, the calculation is done after the last
record has been processed or after LR is set on.
¹ If a control level indicator is used in positions 9 through 11 and positions 7 and
8 are not used (detail time), the operation conditioned by the indicator is done
only on the record that causes a control break or any higher level control break.
¹ If a control level indicator is specified in positions 7 and 8 (total time) and MR is
specified in positions 9 through 11, MR indicates the matching condition of the
previous record and not the one just read that caused the control break. After
54
ILE RPG for AS/400 Reference
Using Indicators
all operations conditioned by control level indicators in positions 7 and 8 are
done, MR then indicates the matching condition of the record just read.
¹ If positions 7 and 8 and positions 9 through 11 are blank, the calculation specified on the line is done at detail calculation time.
Figure 19 and Figure 20 show examples of conditioning indicators.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
IFilenameSqNORiPos1NCCPos2NCCPos3NCC.PFromTo++DField+L1M1FrPlMnZr...*
I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr....
*
* Field indicators can be used to condition operations. Assume the
* program is to find weekly earnings including overtime. The over* time field is checked to determine if overtime was entered.
* If the employee has worked overtime, the field is positive and * indicator 10 is set on. In all cases the weekly regular wage
* is calculated. However, overtime pay is added only if
* indicator 10 is on.
*
ITIME
AB 01
I
1
7 EMPLNO
I
8
10 0OVERTM
10
I
15
20 2RATE
I
21
25 2RATEOT
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
*
* Field indicator 10 was assigned on the input specifications.
* It is used here to condition calculation operations.
*
C
EVAL (H) PAY = RATE * 40
C
10
EVAL (H) PAY = PAY + (OVERTM * RATEOT)
Figure 19. Conditioning Operations (Field Indicators)
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................
I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr....
*
* A record identifying indicator is used to condition an operation.
* When a record is read with a T in position 1, the 01 indicator is
* set on. If this indicator is on, the field named SAVE is added
* to SUM. When a record without T in position 1 is read, the 02
* indicator is set on. The subtract operation, conditioned by 02,
* then performed instead of the add operation.
*
IFILE
AA 01
1 CT
I
OR
02
1NCT
I
10
15 2SAVE
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
*
* Record identifying indicators 01 and 02 are assigned on the input
* specifications. They are used here to condition calculation
* operations.
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
C
01
ADD
SAVE
SUM
8 2
C
02
SUB
SAVE
SUM
8 2
Figure 20. Conditioning Operations (Record Identifying Indicators)
Chapter 4. RPG IV Indicators
55
Using Indicators
Indicators Used in Expressions
Indicators can be used as booleans in expressions in the extended factor 2 field of
the calculation specification. They must be referred to as data (that is, using *IN or
*INxx). The following examples demonstrate this.
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
* In these examples, the IF structure is performed only if 01 is on.
* *IN01 is treated as a boolean with a value of on or off.
* In the first example, the value of the indicator ('0' or '1') is
* checked.
C
IF
*IN01
*
*
*
*
C
In the second example, the logical expression B < A is evaluated.
If true, 01 is set on. If false 01 is set off. This is analogous
to using COMP with A and B and placing 01 in the appropriate
resulting indicator position.
EVAL
*IN01 = B < A
Figure 21. Indicators Used in Expressions
See the expressions chapter and the operation codes chapter in this document for
more examples and further details.
Indicators Conditioning Output
Indicators that you use to specify the conditions under which an output record or an
output field is written must be previously defined in the program. Indicators to condition output are specified in positions 21 through 29. All indicators are valid for
conditioning output.
The indicators you use to condition output must be previously defined as one of the
following types of indicators:
¹ Overflow indicators (file description specifications, “OFLIND(*INxx)” on
page 266)
¹ Record identifying indicators (input specifications, positions 21 and 22)
¹ Control level indicators (input specifications, positions 63 and 64)
¹ Field indicators (input specifications, positions 69 through 74)
¹ Resulting indicators (calculation specifications, positions 71 through 76)
¹ Indicators set by the RPG IV program such as 1P and LR
¹ External indicators set prior to or during program processing
¹ *IN array, *IN(xx) array element, or *INxx field (see “Indicators Referred to As
Data” on page 59 for a description of how an indicator is defined when used
with one of these reserved words).
If an indicator is to condition an entire record, you enter the indicator on the line
that specifies the record type (see Figure 22 on page 58). If an indicator is to condition when a field is to be written, you enter the indicator on the same line as the
field name (see Figure 22 on page 58).
Conditioning indicators are not required on output lines. If conditioning indicators
are not specified, the line is output every time that type of record is checked for
56
ILE RPG for AS/400 Reference
Using Indicators
output. If you specify conditioning indicators, one indicator can be entered in each
of the three separate output indicator fields (positions 22 and 23, 25 and 26, and 28
and 29). If these indicators are on, the output operation is done. An N in the position preceding each indicator (positions 21, 24, or 27) means that the output operation is done only if the indicator is not on (a negative indicator). No output line
should be conditioned by all negative indicators; at least one of the indicators
should be positive. If all negative indicators condition a heading or detail operation,
the operation is done at the beginning of the program cycle when the first page
(1P) lines are written.
You can specify output indicators in an AND/OR relationship by specifying AND/OR
in positions 16 through 18. An unlimited number of AND/OR lines can be used.
AND/OR lines can be used to condition output records, but they cannot be used to
condition fields. However, you can condition a field with more than three indicators
by using the EVAL operation in calculations. The following example illustrates this.
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
* Indicator 20 is set on only if indicators 10, 12, 14,16, and 18
* are set on.
C
EVAL
*IN20 = *IN10 AND *IN12 AND *IN14
C
AND *IN16 AND *IN18
OFilename++DAddN01N02N03Excnam++++.......................................
O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat
* OUTFIELD is conditioned by indicator 20, which effectively
* means it is conditioned by all the indicators in the EVAL
* operation.
OPRINTER
E
O
20
OUTFIELD
Other special considerations you should know about for output indicators are as
follows:
¹ The first page indicator (1P) allows output on the first cycle before the primary
file read, such as printing on the first page. The line conditioned by the 1P indicator must contain constant information used as headings or fields for reserved
words such as PAGE and UDATE. The constant information is specified in the
output specifications in positions 53 through 80. If 1P is used in an OR relationship with an overflow indicator, the information is printed on every page (see
Figure 23 on page 58). Use the 1P indicator only with heading or detail output
lines. It cannot be used to condition total or exception output lines or should not
be used in an AND relationship with control level indicators.
¹ If certain error conditions occur, you might not want output operation processed. Use halt indicators to prevent the data that caused the error from being
used (see Figure 24 on page 59).
¹ To condition certain output records on external conditions, use external indicators to condition those records.
See the Printer File section in the ILE RPG for AS/400 Programmer's Guide for a
discussion of the considerations that apply to assigning overflow indicators on the
output specifications.
Chapter 4. RPG IV Indicators
57
Using Indicators
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
OFilename++DF..N01N02N03Excnam++++B++A++Sb+Sa+...........................
O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat
*
* One indicator is used to condition an entire line of printing.
* When 44 is on, the fields named INVOIC, AMOUNT, CUSTR, and SALSMN
* are all printed.
*
OPRINT
D
44
1
O
INVOIC
10
O
AMOUNT
18
O
CUSTR
65
O
SALSMN
85
*
* A control level indicator is used to condition when a field should
* be printed. When indicator 44 is on, fields INVOIC, AMOUNT, and
* CUSTR are always printed. However, SALSMN is printed for the
* first record of a new control group only if 44 and L1 are on.
*
OPRINT
D
44
1
O
INVOIC
10
O
AMOUNT
18
O
CUSTR
65
O
L1
SALSMN
85
Figure 22. Output Indicators
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
OFilename++DF..N01N02N03Excnam++++B++A++Sb+Sa+...........................
O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat
*
* The 1P indicator is used when headings are to be printed
* on the first page only.
*
OPRINT
H
1P
3
O
8 'ACCOUNT'
*
* The 1P indicator and an overflow indicator can be used to print
* headings on every page.
*
OPRINT
H
1P
3 1
O
OR
OF
O
8 'ACCOUNT'
Figure 23. 1P Indicator
58
ILE RPG for AS/400 Reference
Indicators Referred to As Data
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................
I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr....
*
* When an error condition (zero in FIELDB) is found, the halt
* indicator is set on.
*
IDISK
AA 01
I
1
3 FIELDA
L1
I
4
8 0FIELDB
H1
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
*
* When H1 is on, all calculations are bypassed.
*
C
H1
GOTO
END
C
:
C
:
Calculations
C
:
C
END
TAG
OFilename++DF..N01N02N03Excnam++++B++A++Sb+Sa+...........................
O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat
*
* FIELDA and FIELDB are printed only if H1 is not on.
* Use this general format when you do not want information that
* is in error to be printed.
*
OPRINT
H
L1
0 2 01
O
50 'HEADING'
O
D
01NH1
1 0
O
FIELDA
5
O
FIELDB
Z
15
Figure 24. Preventing Fields from Printing
Indicators Referred to As Data
An alternative method of referring to and manipulating RPG IV indicators is provided by the RPG IV reserved words *IN and *INxx.
*IN
The array *IN is a predefined array of 99 one-position, character elements representing the indicators 01 through 99. The elements of the array should contain only
the character values '0' (zero) or '1' (one).
The specification of the *IN array or the *IN(xx) variable-index array element as a
field in an input record, as a result field, or as factor 1 in a PARM operation defines
indicators 01 through 99 for use in the program.
The operations or references valid for an array of single character elements are
valid with the array *IN except that the array *IN cannot be specified as a subfield
in a data structure, or as a result field of a PARM operation.
Chapter 4. RPG IV Indicators
59
Indicators Referred to As Data
*INxx
The field *INxx is a predefined one-position character field where xx represents any
one of the RPG IV indicators except 1P or MR.
The specification of the *INxx field or the *IN(n) fixed-index array element (where n
= 1 - 99) as a field in an input record, as a result field, or as factor 1 in a PARM
operation defines the corresponding indicator for use in the program.
You can specify the field *INxx wherever a one-position character field is valid
except that *INxx cannot be specified as a subfield in a data structure, as the result
field of a PARM operation, or in a SORTA operation.
Additional Rules
Remember the following rules when you are working with the array *IN, the array
element *IN(xx) or the field *INxx:
¹ Moving a character '0' (zero) or *OFF to any of these fields sets the corresponding indicator off.
¹ Moving a character '1' (one) or *ON to any of these fields sets the corresponding indicator on.
¹ Do not move any value, other than '0' (zero) or '1' (one), to *INxx. Any subsequent normal RPG IV indicator tests may yield unpredictable results.
See Figure 25 on page 61 for some examples of indicators referred to as data.
60
ILE RPG for AS/400 Reference
Summary of Indicators
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
*
* When this program is called, a single parameter is passed to
* control some logic in the program. The parameter sets the value
* of indicator 50. The parameter must be passed with a character
* value of 1 or 0.
*
C
*ENTRY
PLIST
C
*IN50
PARM
SWITCH
1
*
*
* Subroutine SUB1 uses indicators 61 through 68. Before the
* subroutine is processed, the status of these indicators used in
* the mainline program is saved. (Assume that the indicators are
* set off in the beginning of the subroutine.) After the subroutine
* is processed, the indicators are returned to their original state.
*
*
C
MOVEA
*IN(61)
SAV8
8
C
EXSR
SUB1
C
MOVEA
SAV8
*IN(61)
*
* A code field (CODE) contains a numeric value of 1 to 5 and is
* used to set indicators 71 through 75. The five indicators are set
* off. Field X is calculated as 70 plus the CODE field. Field X is
* then used as the index into the array *IN. Different subroutines
* are then used based on the status of indicators 71 through 75.
*
C
MOVEA
'00000'
*IN(71)
C
70
ADD
CODE
X
3 0
C
MOVE
*ON
*IN(X)
C
71
EXSR
CODE1
C
72
EXSR
CODE2
C
73
EXSR
CODE3
C
74
EXSR
CODE4
C
75
EXSR
CODE5
Figure 25. Examples of Indicators Referred to as Data
Summary of Indicators
Table 3 on page 62 and Table 4 on page 62 show summaries of where RPG IV
indicators are defined, what the valid entries are, where the indicators are used,
and when the indicators are set on and off. Table 4 indicates the primary condition
that causes each type of indicator to be set on and set off by the RPG IV program.
“Function Key Indicators” on page 51 lists the function key indicators and the corresponding function keys.
Chapter 4. RPG IV Indicators
61
Summary of Indicators
Table 3. Indicator Entries and Uses
Where Defined/Used
User
Defined
RPG
Defined
Overflow indicator, file
description specifications, OFLIND keyword
X
Record identifying indicator input specifications, positions 21-22
X
1P
H1-H9
L1-L9
LR
MR
OA-OG
OV
U1-U8
KA-KN
KP-KY
RT
X
X
Control level, input specifications, positions
63-64
X
X
X
X
X
X
X
Field level, input specifications, positions 69-74
X
X
Resulting indicator, calculation specifications,
positions 71-76
X
X
Internal Indicator
X
X
X1
X
X
X
File conditioning, file
description specifications
X
X
Control level, calculation
specifications, positions
7-8
Conditioning indicators,
calculation specifications, positions 9-11
X
Output indicators, output
specifications, positions
21-29
X
X4
X
X
X
X
X
X2
X
External Indicator
File record relation, input
specifications 67-683
Used
01-99
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
Notes:
1. The overflow indicator must be defined on the file description specification first.
2. KA through KN and KP through KY can be used as resulting indicators only with the SETOFF operation.
3. Only a record identifying indicator from a main or OR record can be used to condition a control or match field.
L1 or L9 cannot be used to condition a control or match field.
4. The 1P indicator is allowed only on heading and detail lines.
Table 4 (Page 1 of 2). When Indicators Are Set On and Off by the RPG IV Logic Cycle
|
|
|
|
|
|
Type of Indicator
Set On
Set Off
Overflow
When printing on or spacing or skipping
past the overflow line.
OA-OG, OV: After the following heading
and detail lines are completed,
or after the file is opened unless
the H-specification keyword
OPENOPT(*NOINZOFL) is used.
01-99: By the user.
62
ILE RPG for AS/400 Reference
Summary of Indicators
Table 4 (Page 2 of 2). When Indicators Are Set On and Off by the RPG IV Logic Cycle
Type of Indicator
Set On
Set Off
Record identifying
When specified primary / secondary record
has been read and before total calculations are processed; immediately after
record is read from a full procedural file.
Before the next primary/secondary record
is read during the next processing cycle.
Control level
When the value in a control field changes.
All lower level indicators are also set on.
At end of following detail cycle.
Field indicator
By blank or zero in specified fields, by plus
in specified field, or by minus in specified
field.
Before this field status is to be tested the
next time.
Resulting
When the calculation is processed and the
condition that the indicator represents is
met.
The next time a calculation is processed
for which the same indicator is specified as
a resulting indicator and the specified condition is not met.
Function key
When the corresponding function key is
pressed for WORKSTN files and at subsequent reads to associated subfiles.
By SETOFF or move fields logic for a
WORKSTN file.
External U1-U8
By CL command prior to beginning the
program, or when used as a resulting or a
field indicator.
By CL command prior to beginning the
program, or when used as a resulting or
when used as a resulting or a field indicator.
H1-H9
As specified by programmer.
When the continue option is selected as a
response to a message, or by the programmer.
RT
As specified by programmer.
When the program is called again.
Internal Indicators
1P
At beginning of processing before any
input records are read.
Before the first record is read.
LR
After processing the last
primary/secondary record of the last file or
by the programmer.
At the beginning of processing, or by the
programmer.
MR
If the match field contents of the record of
a secondary file correspond to the match
field contents of a record in the primary
file.
When all total calculations and output are
completed for the last record of the
matching group.
Chapter 4. RPG IV Indicators
63
Summary of Indicators
64
ILE RPG for AS/400 Reference
File Exception/Errors
Chapter 5. File and Program Exception/Errors
RPG categorizes exception/errors into two classes: program and file. Information on
file and program exception/errors is made available to an RPG IV program using
file information data structures and program status data structures, respectively.
File and Program exception/error subroutines may be specified to handle these
types of exception/errors.
File Exception/Errors
Some examples of file exception/errors are: undefined record type, an error in
trigger program, an I/O operation to a closed file, a device error, and an array/table
load sequence error. They can be handled in one of the following ways:
¹ The operation code extender 'E' can be specified. When specified, before the
operation begins, this extender sets the %ERROR and %STATUS built-in functions to return zero. If an exception/error occurs during the operation, then after
the operation %ERROR returns '1' and %STATUS returns the file status. The
optional file information data structure is updated with the exception/error information. You can determine the action to be taken by testing %ERROR and
%STATUS.
¹ An indicator can be specified in positions 73 and 74 of the calculation specifications for an operation code. This indicator is set on if an exception/error occurs
during the processing of the specified operation. The optional file information
data structure is updated with the exception/error information. You can determine the action to be taken by testing the indicator.
¹ You can create a user-defined ILE exception handler that will take control when
an exception occurs. For more information, see ILE RPG for AS/400 Programmer's Guide.
¹ A file exception/error subroutine can be specified. The subroutine is defined by
the INFSR keyword on a file description specification with the name of the subroutine that is to receive the control. Information regarding the file
exception/error is made available through a file information data structure that
is specified with the INFDS keyword on the file description specification. You
can also use the %STATUS built-in function, which returns the most recent
value set for the program or file status. If a file is specified, %STATUS returns
the value contained in the INFDS *STATUS field for the specified file.
¹ If the indicator, the 'E' extender,or the file exception/error subroutine is not
present, any file exception/errors are handled by the RPG IV default error
handler.
File Information Data Structure
A file information data structure (INFDS) can be defined for each file to make file
exception/error and file feedback information available to the program. The file
information data structure, which must be unique for each file, must be defined in
the main source section. The same INFDS is used by all procedures using the files.
The INFDS contains the following feedback information:
¹ File Feedback (length is 80)
 Copyright IBM Corp. 1994, 1999
65
File Exception/Errors
¹ Open Feedback (length is 160)
¹ Input/Output Feedback (length is 126)
¹ Device Specific Feedback (length is variable)
¹ Get Attributes Feedback (length is variable)
Note: The get attributes feedback uses the same positions in the INFDS as the
input/output feedback and device specific feedback. This means that if you
have a get attributes feedback, you cannot have input/output feedback or
device feedback, and vice versa.
The length of the INFDS depends on what fields you have declared in your INFDS.
The minimum length of the INFDS is 80.
File Feedback Information
The file feedback information starts in position 1 and ends in position 80 in the file
information data structure. The file feedback information contains data about the file
which is specific to RPG. This includes information about the error/exception that
identifies:
¹ The name of the file for which the exception/error occurred
¹ The record being processed when the exception/error occurred or the record
that caused the exception/error
¹ The last operation being processed when the exception/error occurred
¹ The status code
¹ The RPG IV routine in which the exception/error occurred.
The fields from position 1 to position 66 in the file feedback section of the INFDS
are always provided and updated even if INFDS is not specified in the program.
The fields from position 67 to position 80 of the file feedback section of the INFDS
are only updated after a POST operation to a specific device.
If INFDS is not specified, the information in the file feedback section of the INFDS
can be output using the DUMP operation. For more information see “DUMP
(Program Dump)” on page 525.
Overwriting the file feedback section of the INFDS may cause unexpected results in
subsequent error handling and is not recommended.
The location of some of the more commonly used subfields in the file feedback
section of the INFDS is defined by special keywords. The contents of the file feedback section of the INFDS along with the special keywords and their descriptions
can be found in the following tables:
Table 5 (Page 1 of 3). Contents of the File Feedback Information Available in the File Information Data Structure (INFDS)
From
(Pos.
26-32)
To
(Pos.
33-39)
1
9
66
Format
Length Keyword
Information
8
Character
8
The first 8 characters of the file name.
9
Character
1
ILE RPG for AS/400 Reference
*FILE
Open indication (1 = open).
File Exception/Errors
Table 5 (Page 2 of 3). Contents of the File Feedback Information Available in the File Information Data Structure (INFDS)
From
(Pos.
26-32)
To
(Pos.
33-39)
10
Format
Length Keyword
Information
10
Character
1
End of file (1 = end of file)
11
15
Zoned decimal
5,0
*STATUS
Status code. For a description of these codes, see
“File Status Codes” on page 77.
16
21
Character
6
*OPCODE
Operation code The first five positions (left-adjusted)
specify the type of operation by using the character
representation of the calculation operation codes.
For example, if a READE was being processed,
READE is placed in the leftmost five positions. If the
operation was an implicit operation (for example, a
primary file read or update on the output specifications), the equivalent operation code is generated
(such as READ or UPDAT) and placed in location
*OPCODE. Operation codes which have 6 letter
names will be shortened to 5 letters.
DELETE
DELET
EXCEPT EXCPT
READPE REDPE
UNLOCK UNLCK
UPDATE UPDAT
The remaining position contains one of the
following:
|
|
|
|
|
|
|
|
|
|
|
*ROUTINE
F
The last operation was specified for a file
name.
R
The last operation was specified for a
record.
I
The last operation was an implicit file
operation.
22
29
Character
8
First 8 characters of the name of the routine
(including a subprocedure) in which the file operation was done.
30
37
Character
8
If OPTION(*NOSRCSTMT) is specified, this is the
source listing line number of the file operation. If
OPTION(*SRCSTMT) is specified, this is the source
listing statement number of the file operation. The
full statement number is included when it applies to
the root source member. If the statement number is
greater than 6 digits, that is, it includes a source ID
other than zero, the first 2 positions of the 8-byte
feedback area will have a "+ " indicating that the
rest of the statement number is stored in positions
53-54.
38
42
Zoned decimal
5,0
User-specified reason for error on SPECIAL file.
Chapter 5. File and Program Exception/Errors
67
File Exception/Errors
Table 5 (Page 3 of 3). Contents of the File Feedback Information Available in the File Information Data Structure (INFDS)
From
(Pos.
26-32)
To
(Pos.
33-39)
38
Format
Length Keyword
Information
45
Character
8
For a program described file the record identifying
indicator is placed left-adjusted in the field; the
remaining six positions are filled with blanks. For an
externally described file, the first 8 characters of the
name of the record being processed when the
exception/error occurred.
46
52
Character
7
Machine or system message number.
|
|
53
54
Zoned decimal
2, 0
Source Id matching the statement number from
positions 30-37.
|
55
66
Character
12
Unused.
*RECORD
Table 6. Contents of the File Feedback Information Available in the File-Information Data Structure (INFDS) Valid
after a POST
From
(Pos.
26-32)
To
(Pos.
33-39)
67
Format
Length Keyword
Information
70
Zoned decimal
4,0
*SIZE
Screen size (product of the number of rows and the
number of columns on the device screen).
71
72
Zoned decimal
2,0
*INP
The display's keyboard type. Set to 00 if the keyboard is alphanumeric or katakana. Set to 10 if the
keyboard is ideographic.
73
74
Zoned decimal
2,0
*OUT
The display type. Set to 00 if the display is alphanumeric or katakana. Set to 10 if the display is
ideographic. Set to 20 if the display is DBCS.
75
76
Zoned decimal
2,0
*MODE
Always set to 00.
INFDS File Feedback Example: To specify an INFDS which contains fields in the
file feedback section, you can make the following entries:
¹ Specify the INFDS keyword on the file description specification with the name
of the file information data structure
¹ Specify the file information data structure and the subfields you wish to use on
a definition specification.
¹ Specify special keywords left-adjusted, in the FROM field (positions 26-32) on
the definition specification, or specify the positions of the fields in the FROM
field (position 26-32) and the TO field (position 33-39).
68
ILE RPG for AS/400 Reference
File Exception/Errors
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords+++++++++++++++++++++++++++++Comments++++++++++
FMYFILE
IF
E
DISK
INFDS(FILEFBK)
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++Comments++++++++++
DFILEFBK
DS
D FILE
*FILE
* File name
D OPEN_IND
9
9N
* File open?
D EOF_IND
10
10N
* File at eof?
D STATUS
*STATUS
* Status code
D OPCODE
*OPCODE
* Last opcode
D ROUTINE
*ROUTINE
* RPG Routine
D LIST_NUM
30
37
* Listing line
D SPCL_STAT
38
42S 0
* SPECIAL status
D RECORD
*RECORD
* Record name
D MSGID
46
52
* Error MSGID
D SCREEN
*SIZE
* Screen size
D NLS_IN
*INP
* NLS Input?
D NLS_OUT
*OUT
* NLS Output?
D NLS_MODE
*MODE
* NLS Mode?
Figure 26. Example of Coding an INFDS with File Feedback Information
Note: The keywords are not labels and cannot be used to access the subfields.
Short entries are padded on the right with blanks.
Open Feedback Information
Positions 81 through 240 in the file information data structure contain open feedback information. The contents of the file open feedback area are copied by RPG
to the open feedback section of the INFDS whenever the file associated with the
INFDS is opened. This includes members opened as a result of a read operation
on a multi-member processed file.
A description of the contents of the open feedback area, and what file types the
fields are valid for, can be found in the Data Management manual.
INFDS Open Feedback Example: To specify an INFDS which contains fields in
the open feedback section, you can make the following entries:
¹ Specify the INFDS keyword on the file description specification with the name
of the file information data structure
¹ Specify the file information data structure and the subfields you wish to use on
a definition specification.
¹ Use information in the Data Management manual to determine which fields you
wish to include in the INFDS. To calculate the From and To positions (positions
26 through 32 and 33 through 39 of the definition specifications) that specify
the subfields of the open feedback section of the INFDS, use the Offset, Data
Type, and Length given in the Data Management manual and do the following
calculations:
From = 81 + Offset
To = From - 1 + Character_Length
Character_Length = Length (in bytes)
For example, for overflow line number of a printer file, the Data Management
manual gives:
Chapter 5. File and Program Exception/Errors
69
File Exception/Errors
Offset = 107
Data Type is binary
Length = 2
Therefore,
From = 81 + 107 = 188,
To = 188 - 1 + 2 = 189.
See subfield OVERFLOW in example below
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords+++++++++++++++++++++++++++++Comments++++++++++
FMYFILE
O
F 132
PRINTER INFDS(OPNFBK)
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++Comments++++++++++
DOPNFBK
DS
D ODP_TYPE
81
82
* ODP Type
D FILE_NAME
83
92
* File name
D LIBRARY
93
102
* Library name
D SPOOL_FILE
103
112
* Spool file name
D SPOOL_LIB
113
122
* Spool file lib
D SPOOL_NUM
123
124I 0
* Spool file num
D RCD_LEN
125
126I 0
* Max record len
D KEY_LEN
127
128I 0
* Max key len
D MEMBER
129
138
* Member name
D TYPE
147
148I 0
* File type
D ROWS
152
153I 0
* Num PRT/DSP rows
D COLUMNS
154
155I 0
* Num PRT/DSP cols
D NUM_RCDS
156
159I 0
* Num of records
D ACC_TYPE
160
161
* Access type
D DUP_KEY
162
162
* Duplicate key?
D SRC_FILE
163
163
* Source file?
D VOL_OFF
184
185I 0
* Vol label offset
D BLK_RCDS
186
187I 0
* Max rcds in blk
D OVERFLOW
188
189I 0
* Overflow line
D BLK_INCR
190
191I 0
* Blk increment
D FLAGS1
196
196
* Misc flags
D REQUESTER
197
206
* Requester name
D OPEN_COUNT
207
208I 0
* Open count
D BASED_MBRS
211
212I 0
* Num based mbrs
D FLAGS2
213
213
* Misc flags
D OPEN_ID
214
215
* Open identifier
D RCDFMT_LEN
216
217I 0
* Max rcd fmt len
D CCSID
218
219I 0
* Database CCSID
D FLAGS3
220
220
* Misc flags
D NUM_DEVS
227
228I 0
* Num devs defined
Figure 27. Example of Coding an INFDS with Open Feedback Information
Input/Output Feedback Information
Positions 241 through 366 in the file information data structure are used for
input/output feedback information. The contents of the file common input/output
feedback area are copied by RPG to the input/output feedback section of the
INFDS:
¹ If a POST for any file with factor 1 blank has been specified anywhere in your
program:
– only after a POST for the file.
¹ If a POST for any file with factor 1 blank has not been specified anywhere in
your program:
– after each I/O operation, if blocking is not active for the file.
70
ILE RPG for AS/400 Reference
File Exception/Errors
– after the I/O request to data management to get or put a block of data, if
blocking is active for the file.
For more information see “POST (Post)” on page 613.
A description of the contents of the input/output feedback area can be found in the
Data Management manual.
INFDS Input/Output Feedback Example: To specify an INFDS which contains
fields in the input/output feedback section, you can make the following entries:
¹ Specify the INFDS keyword on the file description specification with the name
of the file information data structure
¹ Specify the file information data structure and the subfields you wish to use on
a definition specification.
¹ Use information in the Data Management manual to determine which fields you
wish to include in the INFDS. To calculate the From and To positions (positions
26 through 32 and 33 through 39 of the definition specifications) that specify
the subfields of the input/output feedback section of the INFDS, use the Offset,
Data Type, and Length given in the Data Management manual and do the following calculations:
From = 241 + Offset
To = From - 1 + Character_Length
Character_Length = Length (in bytes)
For example, for device class of a file, the Data Management manual gives:
Offset = 30
Data Type is
Length = 2
Therefore,
From = 241 +
To = 271 - 1
See subfield
character
30 = 271,
+ 2 = 272.
DEV_CLASS in example below
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords+++++++++++++++++++++++++++++Comments++++++++++
FMYFILE
IF
E
DISK
INFDS(MYIOFBK)
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++Comments++++++++++
DMYIOFBK
DS
D
* 241-242 not used
D WRITE_CNT
243
246I 0
* Write count
D READ_CNT
247
250I 0
* Read count
D WRTRD_CNT
251
254I 0
* Write/read count
D OTHER_CNT
255
258I 0
* Other I/O count
D OPERATION
260
260
* Cuurent operation
D IO_RCD_FMT
261
270
* Rcd format name
D DEV_CLASS
271
272
* Device class
D IO_PGM_DEV
273
282
* Pgm device name
D IO_RCD_LEN
283
286I 0
* Rcd len of I/O
Figure 28. Example of Coding an INFDS with Input/Output Feedback Information
Chapter 5. File and Program Exception/Errors
71
File Exception/Errors
Device Specific Feedback Information
The device specific feedback information in the file information data structure starts
at position 367 in the INFDS, and contains input/output feedback information specific to a device.
The length of the INFDS when device specific feedback information is required,
depends on two factors: the device type of the file, and on whether DISK files are
keyed or not. The minimum length is 528; but some files require a longer INFDS.
¹ For WORKSTN files, the INFDS is long enough to hold the device-specific
feedback information for any type of display or ICF file starting at position 241.
For example, if the longest device-specific feedback information requires 390
bytes, the INFDS for WORKSTN files is 630 bytes long (240+390=630).
¹ For externally described DISK files, the INFDS is at least long enough to hold
the longest key in the file beginning at position 401.
More information on the contents and length of the device feedback for database
file, printer files, ICF and display files can be found in the Data Management
manual.
The contents of the device specific input/output feedback area of the file are copied
by RPG to the device specific feedback section of the INFDS:
¹ If a POST for any file with factor 1 blank has been specified anywhere in your
program:
– only after a POST for the file.
¹ If a POST for any file with factor 1 blank has not been specified anywhere in
your program:
– after each I/O operation, if blocking is not active for the file.
– after the I/O request to data management to get or put a block of data, if
blocking is active for the file.
Notes:
1. After each keyed input operation, only the key fields will be updated.
2. After each non-keyed input operation, only the relative record number will be
updated.
For more information see “POST (Post)” on page 613.
INFDS Device Specific Feedback Examples: To specify an INFDS which contains fields in the device-specific feedback section, you can make the following
entries:
¹ Specify the INFDS keyword on the file description specification with the name
of the file information data structure
¹ Specify the file information data structure and the subfields you wish to use on
a definition specification.
¹ Use information in the Data Management manual to determine which fields you
wish to include in the INFDS. To calculate the From and To positions (positions
26 through 32 and 33 through 39 of the definition specifications) that specify
the subfields of the input/output feedback section of the INFDS, use the Offset,
72
ILE RPG for AS/400 Reference
File Exception/Errors
Data Type, and Length given in the Data Management manual and do the following calculations:
From = 367 + Offset
To = From - 1 + Character_Length
Character_Length = Length (in bytes)
For example, for relative record number of a data base file, the Data Management manual gives:
Offset = 30
Data Type is
Length = 4
Therefore,
From = 367 +
To = 397 - 1
See subfield
|
|
|
binary
30 = 397,
+ 4 = 400.
DB_RRN in DBFBK data structure in example below
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords+++++++++++++++++++++++++++++Comments++++++++++
FMYFILE
O
F 132
PRINTER INFDS(PRTFBK)
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++Comments++++++++++
DPRTFBK
DS
D CUR_LINE
367
368I 0
* Current line num
D CUR_PAGE
369
372I 0
* Current page cnt
* If the first bit of PRT_FLAGS is on, the spooled file has been
* deleted. Use TESTB X'80' or TESTB '0' to test this bit.
D PRT_FLAGS
373
373
D PRT_MAJOR
401
402
* Major ret code
D PRT_MINOR
403
404
* Minor ret code
Figure 29. Example of Coding an INFDS with Printer Specific Feedback Information
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords+++++++++++++++++++++++++++++Comments++++++++++
FMYFILE
IF
E
DISK
INFDS(DBFBK)
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++Comments++++++++++
DDBFBK
DS
D FDBK_SIZE
367
370I 0
* Size of DB fdbk
D JOIN_BITS
371
374I 0
* JFILE bits
D LOCK_RCDS
377
378I 0
* Nbr locked rcds
D POS_BITS
385
385
* File pos bits
D DLT_BITS
384
384
* Rcd deleted bits
D NUM_KEYS
387
388I 0
* Num keys (bin)
D KEY_LEN
393
394I 0
* Key length
D MBR_NUM
395
396I 0
* Member number
D DB_RRN
397
400I 0
* Relative-rcd-num
D KEY
401
2400
* Key value (max
D
*
size 2000)
Figure 30. Example of Coding an INFDS with Database Specific Feedback Information
Chapter 5. File and Program Exception/Errors
73
File Exception/Errors
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords+++++++++++++++++++++++++++++Comments++++++++++
FMYFILE
CF
E
WORKSTN INFDS(ICFFBK)
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++Comments++++++++++
DICFFBK
DS
D ICF_AID
369
369
* AID byte
D ICF_LEN
372
375I 0
* Actual data len
D ICF_MAJOR
401
402
* Major ret code
D ICF_MINOR
403
404
* Minor ret code
D SNA_SENSE
405
412
* SNA sense rc
D SAFE_IND
413
413
* Safe indicator
D RQSWRT
415
415
* Request write
D RMT_FMT
416
425
* Remote rcd fmt
D ICF_MODE
430
437
* Mode name
Figure 31. Example of Coding an INFDS with ICF Specific Feedback Information
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords+++++++++++++++++++++++++++++Comments++++++++++
FMYFILE
CF
E
WORKSTN INFDS(DSPFBK)
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++Comments++++++++++
DDSPFBK
DS
D DSP_FLAG1
367
368
* Display flags
D DSP_AID
369
369
* AID byte
D CURSOR
370
371
* Cursor location
D DATA_LEN
372
375I 0
* Actual data len
D SF_RRN
376
377I 0
* Subfile rrn
D MIN_RRN
378
379I 0
* Subfile min rrn
D NUM_RCDS
380
381I 0
* Subfile num rcds
D ACT_CURS
382
383
* Active window
D
* cursor location
D DSP_MAJOR
401
402
* Major ret code
D DSP_MINOR
403
404
* Minor ret code
Figure 32. Example of Coding an INFDS with Display Specific Feedback Information
Get Attributes Feedback Information
The get attributes feedback information in the file information data structure starts
at position 241 in the INFDS, and contains information about a display device or
ICF session (a device associated with a WORKSTN file). The end position of the
get attributes feedback information depends on the length of the data returned by a
get attributes data management operation. The get attributes data management
operation is performed when a POST with a program device specified for factor 1 is
used.
More information about the contents and the length of the get attributes data can
be found in the Data Management manual.
INFDS Get Attributes Feedback Example: To specify an INFDS which contains
fields in the get attributes feedback section, you can make the following entries:
¹ Specify the INFDS keyword on the file description specification with the name
of the file information data structure
¹ Specify the file information data structure and the subfields you wish to use on
a definition specification.
¹ Use information in the Data Management manual to determine which fields you
wish to include in the INFDS. To calculate the From and To positions (positions
74
ILE RPG for AS/400 Reference
File Exception/Errors
26 through 32 and 33 through 39 of the definition specifications) that specify
the subfields of the get attributes feedback section of the INFDS, use the
Offset, Data Type, and Length given in the Data Management manual and do
the following calculations:
From = 241 + Offset
To = From - 1 + Character_Length
Character_Length = Length (in bytes)
For example, for device type of a file, the Data Management manual gives:
Offset = 31
Data Type is
Length = 6
Therefore,
From = 241 +
To = 272 - 1
See subfield
character
31 = 272,
+ 6 = 277.
DEV_TYPE in example below
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords+++++++++++++++++++++++++++++Comments++++++++++
FMYFILE
CF
E
WORKSTN INFDS(DSPATRFBK)
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++Comments++++++++++
DDSPATRFBK
DS
D PGM_DEV
241
250
* Program device
D DEV_DSC
251
260
* Dev description
D USER_ID
261
270
* User ID
D DEV_CLASS
271
271
* Device class
D DEV_TYPE
272
277
* Device type
D REQ_DEV
278
278
* Requester?
D ACQ_STAT
279
279
* Acquire status
D INV_STAT
280
280
* Invite status
D DATA_AVAIL
281
281
* Data available
D NUM_ROWS
282
283I 0
* Number of rows
D NUM_COLS
284
285I 0
* Number of cols
D BLINK
286
286
* Allow blink?
D LINE_STAT
287
287
* Online/offline?
D DSP_LOC
288
288
* Display location
D DSP_TYPE
289
289
* Display type
D KBD_TYPE
290
290
* Keyboard type
D CTL_INFO
342
342
* Controller info
D COLOR_DSP
343
343
* Color capable?
D GRID_DSP
344
344
* Grid line dsp?
* The following fields apply to ISDN.
D ISDN_LEN
385
386I 0
* Rmt number len
D ISDN_TYPE
387
388
* Rmt number type
D ISDN_PLAN
389
390
* Rmt number plan
D ISDN_NUM
391
430
* Rmt number
D ISDN_SLEN
435
436I 0
* Rmt sub-address
D
*
length
D ISDN_STYPE
437
438
* Rmt sub-address
D
*
type
D ISDN_SNUM
439
478
* Rmt sub-address
D ISDN_CON
480
480
* Connection
D ISDN_RLEN
481
482I 0
* Rmt address len
D ISDN_RNUM
483
514
* Rmt address
D ISDN_ELEN
519
520
* Extension len
D ISDN_ETYPE
521
521
* Extension type
D ISDN_ENUM
522
561
* Extension num
D ISDN_XTYPE
566
566
* X.25 call type
D
Figure 33. Example of Coding an INFDS with Display file Get Attributes Feedback Information
Chapter 5. File and Program Exception/Errors
75
File Exception/Errors
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords+++++++++++++++++++++++++++++Comments++++++++++
FMYFILE
CF
E
WORKSTN INFDS(ICFATRFBK)
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++Comments++++++++++
DICFATRFBK
DS
D PGM_DEV
241
250
* Program device
D DEV_DSC
251
260
* Dev description
D USER_ID
261
270
* User ID
D DEV_CLASS
271
271
* Device class
D DEV_TYPE
272
272
* Device type
D REQ_DEV
278
278
* Requester?
D ACQ_STAT
279
279
* Acquire status
D INV_STAT
280
280
* Invite status
D DATA_AVAIL
281
281
* Data available
D SES_STAT
291
291
* Session status
D SYNC_LVL
292
292
* Synch level
D CONV_TYPE
293
293
* Conversation typ
D RMT_LOC
294
301
* Remote location
D LCL_LU
302
309
* Local LU name
D LCL_NETID
310
317
* Local net ID
D RMT_LU
318
325
* Remote LU
D RMT_NETID
326
333
* Remote net ID
D APPC_MODE
334
341
* APPC Mode
D LU6_STATE
345
345
* LU6 conv state
D LU6_COR
346
353
* LU6 conv
D
*
correlator
* The following fields apply to ISDN.
D ISDN_LEN
385
386I 0
* Rmt number len
D ISDN_TYPE
387
388
* Rmt number type
D ISDN_PLAN
389
390
* Rmt number plan
D ISDN_NUM
391
430
* Rmt number
D ISDN_SLEN
435
436I 0
* sub-addr len
D ISDN_STYPE
437
438
* sub-addr type
D ISDN_SNUM
439
478
* Rmt sub-address
D ISDN_CON
480
480
* Connection
D ISDN_RLEN
481
482I 0
* Rmt address len
D ISDN_RNUM
483
514
* Rmt address
D ISDN_ELEN
519
520
* Extension len
D ISDN_ETYPE
521
521
* Extension type
D ISDN_ENUM
522
561
* Extension num
D ISDN_XTYPE
566
566
* X.25 call type
* The following information is available only when program was started
* as result of a received program start request. (P_ stands for protected)
D TRAN_PGM
567
630
*
D P_LUWIDLN
631
631
*
D P_LUNAMELN
632
632
*
D P_LUNAME
633
649
*
D P_LUWIDIN
650
655
*
D P_LUWIDSEQ
656
657I 0
*
Trans pgm name
LUWID fld len
LU-NAME len
LU-NAME
LUWID instance
LUWID seq num
* The following information is available only when a protected conversation
* is started on a remote system. (U_ stands for unprotected)
D U_LUWIDLN
658
658
* LUWID fld len
D U_LUNAMELN
659
659
* LU-NAME len
D U_LUNAME
660
676
* LU-NAME
D U_LUWIDIN
677
682
* LUWID instance
D U_LUWIDSEQ
683
684I 0
* LUWID seq num
Figure 34. Example of Coding an INFDS with ICF file Get Attributes Feedback Information
76
ILE RPG for AS/400 Reference
File Exception/Errors
Blocking Considerations
The fields of the input/output specific feedback in the INFDS and in most cases the
fields of the device specific feedback information section of the INFDS, are not
updated for each operation to the file in which the records are blocked and
unblocked. The feedback information is updated only when a block of records is
transferred between an RPG program and the OS/400 system. However, if you are
doing blocked input on a data base file, the relative record number and the key
value in the data base feedback section of the INFDS are updated:
¹ On every input/output operation, if a POST for any file with factor 1 blank has
not been specified anywhere in your program.
¹ Only after a POST for the file, if a POST for any file with factor 1 blank has
been specified anywhere in your program.
You can obtain valid updated feedback information by using the CL command
OVRDBF (Override with Database File) with SEQONLY(*NO) specified. If you use
a file override command, the ILE RPG compiler does not block or unblock the
records in the file.
For more information on blocking and unblocking of records in RPG see ILE RPG
for AS/400 Programmer's Guide.
File Status Codes
Any code placed in the subfield location *STATUS that is greater than 99 is considered to be an exception/error condition. When the status code is greater than 99;
the error indicator — if specified in positions 73 and 74 — is set on, or the
%ERROR built-in function — if the 'E' extender is specified — is set to return '1';
otherwise, the file exception/error subroutine receives control. Location *STATUS is
updated after every file operation.
You can use the %STATUS built-in function to get information on exception/errors.
It returns the most recent value set for the program or file status. If a file is specified, %STATUS returns the value contained in the INFDS *STATUS field for the
specified file.
The codes in the following tables are placed in the subfield location *STATUS for
the file information data structure:
Table 7. Normal Codes
Device1
Code
RC2
00000
Condition
No exception/error.
00002
W
n/a
Function key used to end display.
00011
W,D,SQ
11xx
End of file on a read (input).
00012
W,D,SQ
n/a
No-record-found condition on a CHAIN, SETLL,
and SETGT operations.
00013
W
n/a
Subfile is full on WRITE operation.
Note:
1“Device”
refers to the devices for which the condition applies. The following abbreviations are used: P
= PRINTER; D = DISK; W = WORKSTN; SP = SPECIAL; SQ = Sequential. The major/minor return
codes under column RC apply only to WORKSTN files. 2The formula mmnn is used to described
major/minor return codes: mm is the major and nn the minor.
Chapter 5. File and Program Exception/Errors
77
File Exception/Errors
Table 8 (Page 1 of 2). Exception/Error Codes
Code
Device1
RC2
Condition
01011
W,D,SQ
n/a
Undefined record type (input record does not
match record identifying indicator).
01021
W,D,SQ
n/a
Tried to write a record that already exists (file
being used has unique keys and key is duplicate,
or attempted to write duplicate relative record
number to a subfile).
01022
D
n/a
Referential constraint error detected on file
member.
01023
D,SQ
n/a
Error in trigger program before file operation performed.
01024
D,SQ
n/a
Error in trigger program after file operation performed.
01031
W,D,SQ
n/a
Match field out of sequence.
01041
n/a
n/a
Array/table load sequence error.
01042
n/a
n/a
Array/table load sequence error. Alternate collating
sequence used.
01051
n/a
n/a
Excess entries in array/table file.
01071
W,D,SQ
n/a
Numeric sequence error.
011214
W
n/a
No indicator on the DDS keyword for Print key.
011224
W
n/a
No indicator on the DDS keyword for Roll Up key.
011234
W
n/a
No indicator on the DDS keyword for Roll Down
key.
011244
W
n/a
No indicator on the DDS keyword for Clear key.
011254
W
n/a
No indicator on the DDS keyword for Help key.
011264
W
n/a
No indicator on the DDS keyword for Home key.
01201
W
34xx
Record mismatch detected on input.
01211
all
n/a
I/O operation to a closed file.
01215
all
n/a
OPEN issued to a file already opened.
012163
all
yes
Error on an implicit OPEN/CLOSE operation.
012173
all
yes
Error on an explicit OPEN/CLOSE operation.
01218
D,SQ
n/a
Record already locked.
01221
D,SQ
n/a
Update operation attempted without a prior read.
01222
D,SQ
n/a
Record cannot be allocated due to referential constraint error
01231
SP
n/a
Error on SPECIAL file.
01235
P
n/a
Error in PRTCTL space or skip entries.
01241
D,SQ
n/a
Record number not found. (Record number specified in record address file is not present in file
being processed.)
01251
W
80xx 81xx
Permanent I/O error occurred.
01255
W
82xx 83xx
Session or device error occurred. Recovery may
be possible.
78
ILE RPG for AS/400 Reference
File Exception/Errors
Table 8 (Page 2 of 2). Exception/Error Codes
Code
Device1
RC2
Condition
01261
W
n/a
Attempt to exceed maximum number of acquired
devices.
01271
W
n/a
Attempt to acquire unavailable device
01281
W
n/a
Operation to unacquired device.
01282
W
0309
Job ending with controlled option.
01284
W
n/a
Unable to acquire second device for single device
file
01285
W
0800
Attempt to acquire a device already acquired.
01286
W
n/a
Attempt to open shared file with SAVDS or IND
options.
01287
W
n/a
Response indicators overlap IND indicators.
01299
W,D,SQ
yes
Other I/O error detected.
01331
W
0310
Wait time exceeded for READ from WORKSTN
file.
Notes:
1. “Device” refers to the devices for which the condition applies. The following abbreviations are used: P =
PRINTER; D = DISK; W = WORKSTN; SP = SPECIAL; SQ = Sequential. The major/minor return codes
under column RC apply only to WORKSTN files.
2. The formula mmnn is used to described major/minor return codes: mm is the major and nn the minor.
3. Any errors that occur during an open or close operation will result in a *STATUS value of 1216 or 1217
regardless of the major/minor return code value.
4. See Figure 9 on page 31 for special handling.
The following table shows the major/minor return code to *STATUS value mapping
for errors that occur to AS/400 programs using WORKSTN files only. See the Data
Management manual for more information on major/minor return codes.
Major
Minor
*STATUS
00,02
all
00000
03
all (except 09,10)
00000
03
09
01282
03
10
01331
04
all
01299
08
all
012851
11
all
00011
34
all
01201
80,81
all
01251
82,83
all
01255
Notes:
1. The return code field will not be updated for a *STATUS value of 1285, 1261, or 1281 because these
conditions are detected before calling data management. To monitor for these errors, you must check
for the *STATUS value and not for the corresponding major/minor return code value.
Chapter 5. File and Program Exception/Errors
79
File Exception/Errors
File Exception/Error Subroutine (INFSR)
To identify the user-written RPG IV subroutine that may receive control following file
exception/errors, specify the INFSR keyword on the File Description specification
with the name of the subroutine that receives control when exception/errors occur
on this file. The subroutine name can be *PSSR, which indicates that the program
exception/error subroutine is given control for the exception/errors on this file.
A file exception/error subroutine (INFSR) receives control when an exception/error
occurs on an implicit (primary or secondary) file operation or on an explicit file operation that does not have an indicator specified in positions 73 and 74. The file
exception/error subroutine can also be run by the EXSR operation code. Any of the
RPG IV operations can be used in the file exception/error subroutine. Factor 1 of
the BEGSR operation and factor 2 of the EXSR operation must contain the name of
the subroutine that receives control (same name as specified with the INFSR
keyword on the file description specifications).
Note: The INFSR keyword cannot be specified if the keyword NOMAIN is specified on the control specification, or if the file is to be accessed by a subprocedure.
The ENDSR operation must be the last specification for the file exception/error subroutine and should be specified as follows:
Position
Entry
6
C
7-11
Blank
12-25
Can contain a label that is used in a GOTO specification within the subroutine.
26-35
ENDSR
36-49
Optional entry to designate where control is to be returned following
processing of the subroutine. The entry must be a 6-position character
field, literal, or array element whose value specifies one of the following
return points.
Note: If the return points are specified as literals, they must be
enclosed in apostrophes. If they are specified as named constants, the constants must be character and must contain only
the return point with no leading blanks. If they are specified in
fields or array elements, the value must be left-adjusted in the
field or array element.
80
ILE RPG for AS/400 Reference
*DETL
Continue at the beginning of detail lines.
*GETIN
Continue at the get input record routine.
*TOTC
Continue at the beginning of total calculations.
*TOTL
Continue at the beginning of total lines.
*OFL
Continue at the beginning of overflow lines.
*DETC
Continue at the beginning of detail calculations.
*CANCL
Cancel the processing of the program.
Blanks
Return control to the RPG IV default error handler. This
applies when factor 2 is a value of blanks and when factor 2
is not specified. If the subroutine was called by the EXSR
File Exception/Errors
operation and factor 2 is blank, control returns to the next
sequential instruction. Blanks are only valid at runtime.
50-76
Blank.
Remember the following when specifying the file exception/error subroutine:
¹ The programmer can explicitly call the file exception/error subroutine by specifying the name of the subroutine in factor 2 of the EXSR operation.
¹ After the ENDSR operation of the file exception/error subroutine is run, the
RPG IV language resets the field or array element specified in factor 2 to
blanks. Thus, if the programmer does not place a value in this field during the
processing of the subroutine, the RPG IV default error handler receives control
following processing of the subroutine unless the subroutine was called by the
EXSR operation. Because factor 2 is set to blanks, the programmer can specify
the return point within the subroutine that is best suited for the exception/error
that occurred. If the subroutine was called by the EXSR operation and factor 2
of the ENDSR operation is blank, control returns to the next sequential instruction following the EXSR operation. A file exception/error subroutine can handle
errors in more than one file.
¹ If a file exception/error occurs during the start or end of a program, control
passes to the RPG IV default error handler, and not to the user-written file
exception/error or subroutine (INFSR).
¹ Because the file exception/error subroutine may receive control whenever a file
exception/error occurs, an exception/error could occur while the subroutine is
running if an I/O operation is processed on the file in error. If an
exception/error occurs on the file already in error while the subroutine is
running, the subroutine is called again; this will result in a program loop unless
the programmer codes the subroutine to avoid this problem. One way to avoid
such a program loop is to set a first-time switch in the subroutine. If it is not the
first time through the subroutine, set on a halt indicator and issue the RETURN
operation as follows:
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
C* If INFSR is already handling the error, exit.
C
ERRRTN
BEGSR
C
SW
IFEQ
'1'
C
SETON
H1
C
RETURN
C* Otherwise, flag the error handler.
C
ELSE
C
MOVE
'1'
SW
C
:
C
:
C
:
C
ENDIF
C* End error processing.
C
MOVE
'0'
SW
C
ENDSR
Figure 35. Setting a First-time Switch
Note: It may not be possible to continue processing the file after an I/O error has
occurred. To continue, it may be necessary to issue a CLOSE operation
and then an OPEN operation to the file.
Chapter 5. File and Program Exception/Errors
81
Program Exception/Errors
Program Exception/Errors
Some examples of program exception/errors are: division by zero, SQRT of a negative number, invalid array index, error on a CALL, error return from called program,
and start position or length out of range for a string operation. They can be handled
in one of the following ways:
¹ The operation code extender 'E' can be specified for some operation codes.
When specified, before the operation begins, this extender sets the %ERROR
and %STATUS built-in functions to return zero. If an exception/error occurs
during the operation, then after the operation %ERROR returns '1' and
%STATUS returns the program status. The optional program status data structure is updated with the exception/error information. You can determine the
action to be taken by testing %ERROR and %STATUS.
¹ An indicator can be specified in positions 73 and 74 of the calculation specifications for some operation codes. This indicator is set on if an exception/error
occurs during the processing of the specified operation. The optional program
status data structure is updated with the exception/error information. You can
determine the action to be taken by testing the indicator.
¹ You can create a user-defined ILE exception handler that will take control when
an exception occurs. For more information, see ILE RPG for AS/400 Programmer's Guide.
¹ A program exception/error subroutine can be specified. You enter *PSSR in
factor 1 of a BEGSR operation to specify this subroutine. Information regarding
the program exception/error is made available through a program status data
structure that is specified with an S in position 23 of the data structure statement on the definition specifications. You can also use the %STATUS built-in
function, which returns the most recent value set for the program or file status.
¹ If the indicator, the 'E' extender, or the program exception/error subroutine is
not present, program exception/errors are handled by the RPG IV default error
handler.
Program Status Data Structure
A program status data structure (PSDS) can be defined to make program
exception/error information available to an RPG IV program. The PSDS must be
defined in the main source section; therefore, there is only one PSDS per module.
A data structure is defined as a PSDS by an S in position 23 of the data structure
statement. A PSDS contains predefined subfields that provide you with information
about the program exception/error that occurred. The location of the subfields in the
PSDS is defined by special keywords or by predefined From and To positions. In
order to access the subfields, you assign a name to each subfield. The keywords
must be specified, left-adjusted in positions 26 through 39.
Information from the PSDS is also provided in a formatted dump. However, a formatted dump might not contain information for fields in the PSDS if the PSDS is not
coded, or the length of the PSDS does not include those fields. For example, if the
PSDS is only 275 bytes long, the time and date or program running will appear as
*N/A*. in the dump, since this information starts at byte 276. For more information
see “DUMP (Program Dump)” on page 525.
82
ILE RPG for AS/400 Reference
Program Exception/Errors
TIP
Call performance with LR on will be greatly improved by having no PSDS, or a
PSDS no longer than 80 bytes, since some of the information to fill the PSDS
after 80 bytes is costly to obtain.
Table 9 provides the layout of the subfields of the data structure and the predefined From and To positions of its subfields that can be used to access information
in this data structure.
Table 9 (Page 1 of 4). Contents of the Program Status Data Structure
|
|
|
|
|
|
|
|
|
|
|
From
(Pos.
26-32)
To
(Pos.
33-39)
1
Format
Length Keyword
Information
10
Character
10
*PROC
Name of the main procedure, if there is one; otherwise, the name associated with the main source
section.
11
15
Zoned decimal
5,0
*STATUS
Status code. For a description of these codes, see
“Program Status Codes” on page 86.
16
20
Zoned decimal
5,0
Previous status code.
21
28
Character
8
RPG IV source listing line number or statement
number. The source listing line number is replaced
by the source listing statement number if
OPTION(*SRCSTMT) is specified instead of
OPTION(*NOSRCSTMT). The full statement
number is included when it applies to the root
source member. If the statement number is greater
than 6 digits (that is, it includes a source ID other
than zero), the first 2 positions of the 8-byte feedback area will have a "+ " indicating that the rest of
statement number is stored in positions 354-355.
Chapter 5. File and Program Exception/Errors
83
Program Exception/Errors
Table 9 (Page 2 of 4). Contents of the Program Status Data Structure
From
(Pos.
26-32)
To
(Pos.
33-39)
29
36
Format
Length Keyword
Information
Character
8
Name of the RPG IV routine in which the exception
or error occurred. This subfield is updated at the
beginning of an RPG IV routine or after a program
call only when the *STATUS subfield is updated
with a nonzero value. The following names identify
the routines:
*ROUTINE
*INIT
Program initialization
*DETL
Detail lines
*GETIN
Get input record
*TOTC
Total calculations
*TOTL
Total lines
*DETC
Detail calculations
*OFL
Overflow lines
*TERM
Program ending
*ROUTINE
Name of program or procedure called
(first 8 characters).
Note: *ROUTINE is not valid unless you use the
normal RPG IV cycle. Logic that takes the
program out of the normal RPG IV cycle
may cause *ROUTINE to reflect an incorrect
value.
37
39
Zoned decimal
3,0
40
42
Character
3
Exception type (CPF for a OS/400 system exception
or MCH for a machine exception).
43
46
Character
4
Exception number. For a CPF exception, this field
contains a CPF message number. For a machine
exception, it contains a machine exception number.
47
50
Character
4
Reserved
51
80
Character
30
Work area for messages. This area is only meant
for internal use by the ILE RPG compiler. The
organization of information will not always be consistent. It can be displayed by the user.
81
90
Character
10
Name of library in which the program is located.
91
170
Character
80
Retrieved exception data. CPF messages are
placed in this subfield when location *STATUS contains 09999.
171
174
Character
4
Identification of the exception that caused RNX9001
exception to be signaled.
175
184
Character
10
Name of file on which the last file operation
occurred (updated only when an error occurs). This
information always contains the full file name.
84
ILE RPG for AS/400 Reference
*PARMS
Number of parameters passed to this program from
a calling program. The value is the same as that
returned by %PARMS. If no information is available,
-1 is returned.
Program Exception/Errors
Table 9 (Page 3 of 4). Contents of the Program Status Data Structure
From
(Pos.
26-32)
To
(Pos.
33-39)
185
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Format
Length Keyword
Information
190
Character
6
Unused.
191
198
Character
8
Date (*DATE format) the job entered the system. In
the case of batch jobs submitted for overnight processing, those that run after midnight will carry the
next day's date. This value is derived from the job
date, with the year expanded to the full four years.
The date represented by this value is the same date
represented by positions 270 - 275.
199
200
Zoned decimal
2,0
First 2 digits of a 4-digit year. The same as the first
2 digits of *YEAR. This field applies to the century
part of the date in positions 270 to 275. For
example, for the date 1999-06-27, UDATE would be
990627, and this century field would be 19. The
value in this field in conjunction with the value in
positions 270 - 275 has the combined information of
the value in positions 191 -198.
|
|
|
Note: This century field does not apply to the
dates in positions 276 to 281, or positions
288 to 293.
201
208
Character
8
Name of file on which the last file operation
occurred (updated only when an error occurs). This
file name will be truncated if a long file name is
used. See positions 175-184 for long file name
information.
209
243
Character
35
Status information on the last file used. This information includes the status code, the RPG IV
opcode, the RPG IV routine name, the source listing
line number or statement number, and record name.
It is updated only when an error occurs.
|
Note: The opcode name is in the same form as
*OPCODE in the INFDS
|
|
|
|
|
|
|
|
|
|
The source listing line number is replaced by the
source listing statement number if
OPTION(*SRCSTMT) is specified instead of
OPTION(*NOSRCSTMT). The full statement
number is included when it applies to the root
source member. If the statement number is greater
than 6 digits (that is, it includes a source ID other
than zero), the first 2 positions of the 8-byte feedback area will have a "+ " indicating that the rest of
statement number is stored in positions 356-357.
244
253
Character
10
Job name.
254
263
Character
10
User name from the user profile.
264
269
Zoned decimal
6,0
Job number.
Chapter 5. File and Program Exception/Errors
85
Program Exception/Errors
Table 9 (Page 4 of 4). Contents of the Program Status Data Structure
From
(Pos.
26-32)
To
(Pos.
33-39)
|
|
|
|
|
|
|
270
|
|
|
|
|
|
Format
Length Keyword
Information
275
Zoned decimal
6,0
Date (in UDATE format) the program started
running in the system (UDATE is derived from this
date). See “User Date Special Words” on page 7
for a description of UDATE. This is commonly
known as the 'job date'. The date represented by
this value is the same date represented by positions
191 - 198.
276
281
Zoned decimal
6,0
Date of program running (the system date in
UDATE format). If the year part of this value is
between 40 and 99, the date is between 1940 and
1999. Otherwise the date is between 2000 and
2039. The 'century' value in positions 199 - 200
does not apply to this field.
282
287
Zoned decimal
6,0
Time (in the format hhmmss) of the program
running.
288
293
Character
6
Date (in UDATE format) the program was compiled.
If the year part of this value is between 40 and 99,
the date is between 1940 and 1999. Otherwise the
date is between 2000 and 2039. The 'century' value
in positions 199 - 200 does not apply to this field.
294
299
Character
6
Time (in the format hhmmss) the program was compiled.
300
303
Character
4
Level of the compiler.
304
313
Character
10
Source file name.
314
323
Character
10
Source library name.
324
333
Character
10
Source file member name.
334
343
Character
10
Program containing procedure.
344
353
Character
10
Module containing procedure.
354
429
Character
76
Unused.
|
|
354
355
Zoned decimal
2, 0
Source Id matching the statement number from
positions 21-28.
|
|
356
357
Zoned decimal
2, 0
Source Id matching the statement number from
positions 228-235.
|
358
367
Character
10
Current user profile name.
|
368
429
Character
62
Unused.
|
|
|
|
|
Program Status Codes
Any code placed in the subfield location *STATUS that is greater than 99 is considered to be an exception/error condition. When the status code is greater than 99;
the error indicator — if specified in positions 73 and 74 — is set on, or the
%ERROR built-in function — if the 'E' extender is specified — is set to return '1';
otherwise, the program exception/error subroutine receives control. Location
*STATUS is updated when an exception/error occurs.
86
ILE RPG for AS/400 Reference
Program Exception/Errors
The %STATUS built-in function returns the most recent value set for the program or
file status.
The following codes are placed in the subfield location *STATUS for the program
status data structure:
Normal Codes
|
Code
Condition
00000
No exception/error occurred
00001
Called program returned with the LR indicator on.
00050
Conversion resulted in substitution.
Exception/Error Codes
Code
Condition
00100
Value out of range for string operation
00101
Negative square root
00102
Divide by zero
00103
An intermediate result is not large enough to contain the result.
00104
Float underflow. An intermediate value is too small to be contained in
the intermediate result field.
00112
Invalid Date, Time or Timestamp value.
00113
Date overflow or underflow. (For example, when the result of a Date calculation results in a number greater than *HIVAL or less than *LOVAL.)
00114
Date mapping errors, where a Date is mapped from a 4-character year
to a 2-character year, and the date range is not 1940-2039.
00115
Variable-length field has a current length that is not valid.
00120
Table or array out of sequence.
00121
Array index not valid
00122
OCCUR outside of range
00123
Reset attempted during initialization step of program
00202
Called program or procedure failed; halt indicator (H1 through H9) not
on
00211
Error calling program or procedure
00222
Pointer or parameter error
00231
Called program or procedure returned with halt indicator on
00232
Halt indicator on in this program
00233
Halt indicator on when RETURN operation run
00299
RPG IV formatted dump failed
00333
Error on DSPLY operation
00401
Data area specified on IN/OUT not found
00402
*PDA not valid for non-prestart job
Chapter 5. File and Program Exception/Errors
87
Program Exception/Errors
00411
Data area type or length does not match
00412
Data area not locked for output
00413
Error on IN/OUT operation
00414
User not authorized to use data area
00415
User not authorized to change data area
00421
Error on UNLOCK operation
00425
Length requested for storage allocation is out of range
00426
Error encountered during storage management operation
00431
Data area previously locked by another program
00432
Data area locked by program in the same process
00450
Character field not entirely enclosed by shift-out and shift-in characters
00501
Failure to retrieve sort sequence.
00502
Failure to convert sort sequence.
00802
Commitment control not active.
00803
Rollback operation failed.
00804
Error occurred on COMMIT operation
00805
Error occurred on ROLBK operation
00907
Decimal data error (digit or sign not valid)
00970
The level number of the compiler used to generate the program does
not agree with the level number of the RPG IV run-time subroutines.
09998
Internal failure in ILE RPG compiler or in run-time subroutines
09999
Program exception in system routine.
PSDS Example
To specify a PSDS in your program, you code the program status data structure
and the subfields you wish to use on a definition specification.
88
ILE RPG for AS/400 Reference
Program Exception/Errors
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++Comments++++++++++
DMYPSDS
SDS
D PROC_NAME
*PROC
* Procedure name
D PGM_STATUS
*STATUS
* Status code
D PRV_STATUS
16
20S 0
* Previous status
D LINE_NUM
21
28
* Src list line num
D ROUTINE
*ROUTINE
* Routine name
D PARMS
*PARMS
* Num passed parms
D EXCP_TYPE
40
42
* Exception type
D EXCP_NUM
43
46
* Exception number
D PGM_LIB
81
90
* Program library
D EXCP_DATA
91
170
* Exception data
D EXCP_ID
171
174
* Exception Id
D DATE
191
198
* Date (*DATE fmt)
D YEAR
199
200S 0
* Year (*YEAR fmt)
D LAST_FILE
201
208
* Last file used
D FILE_INFO
209
243
* File error info
D JOB_NAME
244
253
* Job name
D USER
254
263
* User name
D JOB_NUM
264
269S 0
* Job number
D JOB_DATE
270
275S 0
* Date (UDATE fmt)
D RUN_DATE
276
281S 0
* Run date (UDATE)
D RUN_TIME
282
287S 0
* Run time (UDATE)
D CRT_DATE
288
293
* Create date
D CRT_TIME
294
299
* Create time
D CPL_LEVEL
300
303
* Compiler level
D SRC_FILE
304
313
* Source file
D SRC_LIB
314
323
* Source file lib
D SRC_MBR
324
333
* Source file mbr
D PROC_PGM
334
343
* Pgm Proc is in
D PROC_MOD
344
353
* Mod Proc is in
Figure 36. Example of Coding a PSDS
Note: The keywords are not labels and cannot be used to access the subfields.
Short entries are padded on the right with blanks.
Program Exception/Error Subroutine
To identify the user-written RPG IV subroutine that is to receive control when a
program exception/error occurs, specify *PSSR in factor 1 of the subroutine's
BEGSR operation. If an indicator is not specified in positions 73 and 74 for the
operation code or if an exception occurs that is not expected for the operation code
(that is, an array indexing error during a SCAN operation), control is transferred to
this subroutine when a program exception/error occurs. In addition, the subroutine
can also be called by the EXSR operation. *PSSR can be specified on the INFSR
keyword on the file description specifications and receives control if a file
exception/error occurs.
Any of the RPG IV operation codes can be used in the program exception/error
subroutine. The ENDSR operation must be the last specification for the subroutine,
and the factor 2 entry on the ENDSR operation specifies the return point following
the running of the subroutine. For a discussion of the valid entries for factor 2, see
“File Exception/Error Subroutine (INFSR)” on page 80.
Remember the following when specifying a program exception/error subroutine:
¹ You can explicitly call the *PSSR subroutine by specifying *PSSR in factor 2 of
the EXSR operation.
Chapter 5. File and Program Exception/Errors
89
Program Exception/Errors
¹ After the ENDSR operation of the *PSSR subroutine is run, the RPG IV language resets the field, subfield, or array element specified in factor 2 to blanks.
This allows you to specify the return point within the subroutine that is best
suited for the exception/error that occurred. If factor 2 contains blanks at the
end of the subroutine, the RPG IV default error handler receives control; if the
subroutine was called by an EXSR or CASxx operation, control returns to the
next sequential instruction following the EXSR or ENDCS.
¹ Because the program exception/error subroutine may receive control whenever
a non-file exception/error occurs, an exception/error could occur while the subroutine is running. If an exception/error occurs while the subroutine is running,
the subroutine is called again; this will result in a program loop unless the programmer codes the subroutine to avoid this problem.
¹ If you have used the OPTIMIZE(*FULL) option on either the CRTBNDRPG or
the CRTRPGMOD command, you have to declare all fields that you refer to
during exception handling with the NOOPT keyword in the definition specification for the field. This will ensure that when you run your program, the fields
referred to during exception handling will have current values.
¹ A *PSSR can be defined in a subprocedure, and each subprocedure can have
its own *PSSR. Note that the *PSSR in a subprocedure is local to that subprocedure. If you want the subprocedures to share the same exception routine
then you should have each *PSSR call a shared procedure.
90
ILE RPG for AS/400 Reference
Subprocedure Definition
Chapter 6. Subprocedures
A subprocedure is a procedure specified after the main source section. It can only
be called using a bound call. Subprocedures differ from main procedures in several
respects, the main difference being that subprocedures do not (and cannot) use the
RPG cycle while running.
All subprocedures must have a corresponding prototype in the definition specifications of the main source section. The prototype is used by the compiler to call the
program or procedure correctly, and to ensure that the caller passes the correct
parameters.
This chapter discusses the following aspects of subprocedures:
¹ Subprocedure definition
¹ NOMAIN modules
¹ Comparison with subroutines
Subprocedure Definition
Subprocedures are defined after the main source section. Figure 37 shows a subprocedure, highlighting the different parts of it.
* Prototype for procedure FUNCTION
D FUNCTION
PR
10I 0
D
TERM1
5I 0 VALUE
D
TERM2
5I 0 VALUE
D
TERM3
5I 0 VALUE
.1/
P Function
B
.2/
*------------------------------------------------------------* This procedure performs a function on the 3 numeric values
* passed to it as value parameters.
*
* This illustrates how a procedure interface is specified for a
* procedure and how values are returned from a procedure.
*------------------------------------------------------------D Function
PI
10I 0
.3/
D
Term1
5I 0 VALUE
D
Term2
5I 0 VALUE
D
Term3
5I 0 VALUE
D Result
S
10I 0
.4/
C
EVAL
Result = Term1 ** 2 * 17
C
+ Term2
* 7
.5/
C
+ Term3
C
RETURN
Result * 45 + 23
P
E
.6/
Figure 37. Example of a Subprocedure
.1/
A Prototype which specifies the name, return value if any, and parameters if any.
.2/
A Begin-Procedure specification (B in position 24 of a procedure specification)
 Copyright IBM Corp. 1994, 1999
91
Subprocedure Definition
.3/
A Procedure-Interface definition, which specifies the return value and
parameters, if any. The procedure interface must match the corresponding prototype. The procedure-interface definition is optional if the
subprocedure does not return a value and does not have any parameters that are passed to it.
.4/
Other definition specifications of variables, constants and prototypes
needed by the subprocedure. These definitions are local definitions.
.5/
Any calculation specifications needed to perform the task of the procedure. The calculations may refer to both local and global definitions. Any
subroutines included within the subprocedure are local. They cannot be
used outside of the subprocedure. If the subprocedure returns a value,
then the subprocedure must contain a RETURN operation.
.6/
An End-Procedure specification (E in position 24 of a procedure specification)
Except for the procedure-interface definition, which may be placed anywhere within
the definition specifications, a subprocedure must be coded in the order shown
above.
No cycle code is generated for subprocedures. Consequently, you cannot code:
¹ Prerun-time and compile-time arrays and tables
¹ *DTAARA definitions
¹ Total calculations
The calculation specifications are processed only once and the procedure returns at
the end of the calculation specifications. See “Subprocedure Calculations” on
page 94 for more information.
A subprocedure may be exported, meaning that procedures in other modules in the
program can call it. To indicate that it is to be exported, specify the keyword
EXPORT on the Procedure-Begin specification. If not specified, the subprocedure
can only be called from within the module.
Procedure Interface Definition
If a prototyped procedure has call parameters or a return value, then it must have a
procedure interface definition. A procedure interface definition is a repeat of the
prototype information within the definition of a procedure. It is used to declare the
entry parameters for the procedure and to ensure that the internal definition of the
procedure is consistent with the external definition (the prototype).
You specify a procedure interface by placing PI in the Definition-Type entry (positions 24-25). Any parameter definitions, indicated by blanks in positions 24-25, must
immediately follow the PI specification. The procedure interface definition ends with
the first definition specification with non-blanks in positions 24-25 or by a nondefinition specification.
For more information on procedure interface definitions, see “Procedure Interface”
on page 141.
92
ILE RPG for AS/400 Reference
Subprocedure Definition
Return Values
A procedure that returns a value is essentially a user-defined function, similar to a
built-in function. To define a return value for a subprocedure, you must
1. Define the return value on both the prototype and procedure-interface definitions of the subprocedure.
2. Code a RETURN operation with an expression in the extended-factor 2 field
that contains the value to be returned.
You define the length and the type of the return value on the procedure-interface
specification (the definition specification with PI in positions 24-25). The following
keywords are also allowed:
DATFMT(fmt)
The return value has the date format specified by the keyword.
DIM(N)
The return value is an array with N elements.
LIKE(name)
The return value is defined like the item specified by the keyword.
PROCPTR
The return value is a procedure pointer.
TIMFMT(fmt)
The return value has the time format specified by the keyword.
To return the value to the caller, you must code a RETURN operation with an
expression containing the return value. The expression in the extended-factor 2
field is subject to the same rules as an expression with EVAL. The actual returned
value has the same role as the left-hand side of the EVAL expression, while the
extended factor 2 of the RETURN operation has the same role as the right-hand
side. You must ensure that a RETURN operation is performed if the subprocedure
has a return value defined; otherwise an exception is issued to the caller of the
subprocedure.
Scope of Definitions
Any items defined within a subprocedure are local. If a local item is defined with the
same name as a global data item, then any references to that name inside the
subprocedure use the local definition.
However, keep in mind the following:
¹ Subroutine names and tag names are known only to the procedure in which
they are defined, even those defined in the main procedure.
¹ All fields specified on input and output specifications are global. When a subprocedure uses input or output specifications (for example, while processing a
read operation), the global name is used even if there is a local variable of the
same name.
When using a global KLIST or PLIST in a subprocedure some of the fields may
have the same names as local fields. If this occurs, the global field is used. This
may cause problems when setting up a KLIST or PLIST prior to using it.
For example, consider the following source.
Chapter 6. Subprocedures
93
Subprocedure Definition
* Main procedure definitions
D Fld1
S
D Fld2
S
1A
1A
* Define a global key field list with 2 fields, Fld1 and Fld2
global_kl
KLIST
KFLD
Fld1
KFLD
Fld2
C
C
C
* Subprocedure Section
P Subproc
B
D Fld2
S
1A
* local_kl has one global kfld (fld1) and one local (fld2)
local_kl
KLIST
KFLD
Fld1
KFLD
Fld2
C
C
C
*
*
*
*
C
C
C
Even though Fld2 is defined locally in the subprocedure,
the global Fld2 is used by the global_kl, since global KLISTs
always use global fields. As a result, the assignment to the
local Fld2 will NOT affect the CHAIN operation.
global_kl
EVAL
EVAL
SETLL
Fld1 = 'A'
Fld2 = 'B'
file
* Local KLISTs use global fields only when there is no local
* field of that name. local_kl uses the local Fld2 and so the
* assignment to the local Fld2 WILL affect the CHAIN operation.
C
EVAL
Fld1 = 'A'
C
EVAL
Fld2 = 'B'
C
local_kl
SETLL
file
...
P
E
Figure 38. Scope of Key Fields Inside a Module
For more information on scope, see “Scope of Definitions” on page 114.
Subprocedure Calculations
No cycle code is generated for a subprocedure, and so you must code it differently
than a main procedure. The subprocedure ends when one of the following occurs:
¹ A RETURN operation is processed
¹ The last calculation in the body of the subprocedure is processed.
Figure 39 on page 95 shows the normal processing steps for a subprocedure.
Figure 40 on page 96 shows the exception/error handling sequence.
94
ILE RPG for AS/400 Reference
Subprocedure Definition
Start
First
procedure (main
or sub) called in the
module since program
activation?
• Run module initialization
• Perform data structure and
Yes
No
subfield initialization
• Retrieve external indicators
(U1 through U8) and user date fields
• Open files
• Load data area data
sructures, arrays, and tables
• If there is no *INZSR, store
data structures and variables
for RESET operations
Initialize
automatic variables
First time
subprocedure
has been called?
Yes
• Initialize static variables
• Store variables for RESET
operations on local variables
No
Return operation
Perform calculations once
If subprocedure
returns a value, was a
RETURN operation
done?
Set return value for caller
(if the subprocedure
returns a value)
Yes
Return to caller
No
Signal exception to
caller (subprocedure
ends)
Figure 39. Normal Processing Sequence for a Subprocedure
.1/
Taking the "No" branch means that another procedure has already been
called since the program was activated. You should ensure that you do
not make any incorrect assumptions about the state of files, data areas,
etc., since another procedure may have closed files, or unlocked data
areas.
.2/
If an entry parameter to the main procedure is RESET anywhere in the
module, this will cause an exception. If it is possible that a subprocedure
will be called before the main procedure, it is not advised to RESET any
entry parameters for the main procedure.
Chapter 6. Subprocedures
95
Subprocedure Definition
Exception during
calculations
Program error
and subprocedure
has *PSSR?
Yes
Execute *PSSR
subroutine
No
Percolate exception
(subprocedure ends)
*PSSR reached
ENDSR?
No
Program continues
normally after RETURN
or GOTO
Yes
Signal exception to
caller (subprocedure
ends)
Figure 40. Exception/Error Handling Sequence for a Subprocedure
Here are some points to consider when coding subprocedures:
¹ There is no *INZSR associated with subprocedures. Data is initialized (with
either INZ values or default values) when the subprocedure is first called, but
before the calculations begin.
Note also that if the subprocedure is the first procedure to be called in a
module, the *INZSR of the main procedure (if present) will not be run, although
other initialization of global data will be done. The *INZSR of the main procedure will be run when the main procedure is called.
¹ When a subprocedure returns normally, the return value, if specified on the prototype of the called program or procedure, is passed to the caller. Nothing else
occurs automatically. All files and data areas must be closed manually. Files
must be written out manually. You can set on indicators such as LR, but
program termination will not occur until the main procedure terminates.
¹ Exception handling within a subprocedure differs from a main procedure primarily because there is no default exception handler for subprocedures and so
situations where the default handler would be called for a main procedure correspond to abnormal end of the subprocedure. For example, Factor 2 of an
ENDSR operation for a *PSSR subroutine within a subprocedure must be
blank. A blank factor 2 in a main procedure would result in control being
passed to the default handler. In a subprocedure, if the ENDSR is reached,
then the subprocedure will end abnormally and RNX9001 will be signalled to
the caller of the subprocedure.
You can avoid abnormal termination either by coding a RETURN operation in
the *PSSR, or by coding a GOTO and label in the subprocedure to continue
processing.
¹ The *PSSR error subroutine is local to the subprocedure. Conversely, file errors
are global by definition, and so you cannot code an INFSR in a subprocedure,
nor can you use a file for which an INFSR is coded.
¹ Indicators that control the cycle function solely as conditioning indicators when
used in a NOMAIN module; or in a subprocedure that is active, but where the
main procedure of the module is not. Indicators that control the cycle include:
LR, RT, H1-H9, and control level indicators.
96
ILE RPG for AS/400 Reference
Subprocedures and Subroutines
NOMAIN Module
You can code one or more subprocedures in a module without coding a main procedure. Such a module is called a NOMAIN module, since it requires the specification of the NOMAIN keyword on the control specification. When there is no main
procedure, no cycle code generated for the NOMAIN module.
TIP
You may want to consider making all your modules NOMAIN modules except
the ones that actually contain the program entry procedure for a program. The
lack of the cycle code will reduce the size of the program.
Since there is no main procedure, you are restricted in terms of what can be coded
in the main source section. Specifically, you cannot code specifications for
¹ Primary and secondary files
¹ Detail and total output
¹ Executable calculations (including an initialization subroutine)
¹ *ENTRY PLIST
Instead you would code in the main source section:
¹ Full-procedural files
¹ Input specifications
¹ Definition specifications
¹ Declarative calculations such as DEFINE, KFLD, KLIST, PARM, and PLIST (but
not *ENTRY PLIST)
¹ Exception output
Note: A module with NOMAIN specified will not have a program entry procedure.
Consequently you cannot use the CRTBNDRPG command to compile the
source.
Subprocedures and Subroutines
A subprocedure is similar to a subroutine, except that a subprocedure offers the
following improvements:
¹ You can pass parameters to a subprocedure, even passing by value.
This means that the parameters used to communicate with subprocedures do
not have to be modifiable. Parameters that are passed by reference, as they
are with programs, must be modifiable, and so may be less reliable.
¹ The parameters passed to a subprocedure and those received by it are
checked at compile time for consistency. This helps to reduce run-time errors,
which can be more costly.
¹ You can use a subprocedure like a built-in function in an expression.
When used in this way, they return a value to the caller. This basically allows
you to custom-define any operators you might need in an expression.
Chapter 6. Subprocedures
97
Subprocedures and Subroutines
¹ Names defined in a subprocedure are not visible outside the subprocedure.
This means that there is less chance of the procedure inadvertently changing a
item that is shared by other procedures. Furthermore, the caller of the procedure does not need to know as much about the items used inside the subprocedure.
¹ You can call the subprocedure from outside the module, if it is exported.
¹ You can call subprocedures recursively.
¹ Procedures are defined on a different specification type, namely, procedure
specifications. This different type helps you to immediately recognize that you
are dealing with a separate unit.
Nonetheless, if you do not require the improvements offered by subprocedures, you
should use a subroutine. The processing of a subroutine is much faster than a call
to a subprocedure.
98
ILE RPG for AS/400 Reference
Primary/Secondary Multi-file Processing
Chapter 7. General File Considerations
This chapter contains a more detailed explanation of:
¹ Multi-file Processing
¹ Match fields
¹ Alternate collating sequence
¹ File translation.
Primary/Secondary Multi-file Processing
In an RPG IV program, the processing of a primary input file and one or more secondary input files, with or without match fields, is termed multi-file processing.
Selection of records from more than one file based on the contents of match fields
is known as multi-file processing by matching records. Multi-file processing can be
used with externally described or program described input files that are designated
as primary/secondary files.
Multi-file Processing with No Match Fields
When no match fields are used in multi-file processing, records are selected from
one file at a time. When the records from one file are all processed, the records
from the next file are selected. The files are selected in this order:
1. Primary file, if specified
2. Secondary files in the order in which they are described on the file description
specifications.
Multi-file Processing with Match Fields
When match fields are used in multi-file processing, the program selects the
records for processing according to the contents of the match fields. At the beginning of the first cycle, the program reads one record from every primary/secondary
input file and compares the match fields in the records. If the records are in
ascending order, the program selects the record with the lowest match field. If the
records are in descending order, the program selects the record with the highest
match field.
When a record is selected from a file, the program reads the next record from that
file. At the beginning of the next program cycle, the new record is compared with
the other records in the read area that are waiting for selection, and one record is
selected for processing.
Records without match fields can also be included in the files. Such records are
selected for processing before records with match fields. If two or more of the
records being compared have no match fields, selection of those records is determined by the priority of the files from which the records came. The priority of the
files is:
1. Primary file, if specified
2. Secondary files in the order in which they are described on the file description
specifications.
 Copyright IBM Corp. 1994, 1999
99
Primary/Secondary Multi-file Processing
When the primary file record matches one or more of the secondary records, the
MR (matching record) indicator is set on. The MR indicator is on for detail time
processing of a matching record through the total time that follows the record. This
indicator can be used to condition calculation or output operations for the record
that is selected. When one of the matching records must be selected, the selection
is determined by the priority of the files from which the records came.
Figure 7 on page 27 shows the logic flow of multi-file processing.
A program can be written where only one input file is defined with match fields and
no other input files have match fields. The files without the match fields are then
processed completely according to the previously mentioned priority of files. The file
with the match fields is processed last, and sequence checking occurs for that file.
Assigning Match Field Values (M1-M9)
When assigning match field values (M1 through M9) to fields on the input specifications in positions 65 and 66, consider the following:
¹ Sequence checking is done for all record types with match field specifications.
All match fields must be in the same order, either all ascending or all
descending. The contents of the fields to which M1 through M9 are assigned
are checked for correct sequence. An error in sequence causes the RPG IV
exception/error handling routine to receive control. When the program continues
processing, the next record from the same file is read.
¹ Not all files used in the program must have match fields. Not all record types
within one file must have match fields either. However, at least one record type
from two files must have match fields if files are ever to be matched.
¹ The same match field values must be specified for all record types that are
used in matching. See Figure 41 on page 102.
¹ Date, time, and timestamp match fields with the same match field values (M1
through M9) must be the same type (for example, all date) but can be different
formats.
¹ All character, graphic, or numeric match fields with the same match field values
(M1 through M9) should be the same length and type. If the match field contains packed data, the zoned decimal length (two times packed length - 1) is
used as the length of the match field. It is valid to match a packed field in one
record against a zoned decimal field in another if the digit lengths are identical.
The length must always be odd because the length of a packed field is always
odd.
¹ Record positions of different match fields can overlap, but the total length of all
fields must not exceed 256 characters.
¹ If more than one match field is specified for a record type, all the fields are
combined and treated as one continuous field (see Figure 41 on page 102).
The fields are combined according to descending sequence (M9 to M1) of
matching field values.
¹ Match fields values cannot be repeated in a record.
¹ All match fields given the same matching field value (M1 through M9) are considered numeric if any one of the match fields is described as numeric.
¹ When numeric fields having decimal positions are matched, they are treated as
if they had no decimal position. For instance 3.46 is considered equal to 346.
100
ILE RPG for AS/400 Reference
Primary/Secondary Multi-file Processing
¹ Only the digit portions of numeric match fields are compared. Even though a
field is negative, it is considered to be positive because the sign of the numeric
field is ignored. Therefore, a -5 matches a +5.
¹ Date and time fields are converted to *ISO format for comparisons
¹ Graphic data is compared hexadecimally
¹ Whenever more than one matching field value is used, all match fields must
match before the MR indicator is set on. For example, if match field values M1,
M2, and M3 are specified, all three fields from a primary record must match all
three match fields from a secondary record. A match on only the fields specified by M1 and M2 fields will not set the MR indicator on (see Figure 41 on
page 102).
|
¹ UCS-2 fields cannot be used for matching fields.
¹ Matching fields cannot be used for lookahead fields, and arrays.
¹ Field names are ignored in matching record operations. Therefore, fields from
different record types that are assigned the same match level can have the
same name.
¹ If an alternate collating sequence or a file translation is defined for the program,
character fields are matched according to the alternate sequence specified.
¹ Null-capable fields, character fields defined with ALTSEQ(*NONE), and binary,
float, integer and unsigned fields (B, F, I, or U in position 36 of the input specifications) cannot be assigned a match field value.
¹ Match fields that have no field record relation indicator must be described
before those that do. When the field record relation indicator is used with match
fields, the field record relation indicator should be the same as a record identifying indicator for this file, and the match fields must be grouped according to
the field record relation indicator.
¹ When any match value (M1 through M9) is specified for a field without a field
record relation indicator, all match values used must be specified once without
a field record relation indicator. If all match fields are not common to all
records, a dummy match field should be used. Field record relation indicators
are invalid for externally described files. (see Figure 42 on page 103).
¹ Match fields are independent of control level indicators (L1 through L9).
¹ If multi-file processing is specified and the LR indicator is set on, the program
bypasses the multi-file processing routine.
Figure 43 on page 104 is an example of how match fields are specified.
Chapter 7. General File Considerations
101
Primary/Secondary Multi-file Processing
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++
* The files in this example are externally described (E in position
* 22) and are to be processed by keys (K in position 34).
FMASTER
IP
E
K DISK
FWEEKLY
IS
E
K DISK
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
IRcdname+++....Ri........................................................
I..............Ext-field+..................Field+++++++++L1M1..PlMnZr....
*
MASTER FILE
IEMPMAS
01
I
EMPLNO
M1
I
DIVSON
M3
I
DEPT
M2
IDEPTMS
02
I
EMPLNO
M1
I
DEPT
M2
I
DIVSON
M3
*
WEEKLY FILE
IWEEKRC
03
I
EMPLNO
M1
I
DIVSON
M3
I
DEPT
M2
Figure 41. Match Fields in Which All Values Match
Three files are used in matching records. All the files have three match fields specified, and all use the same values (M1, M2, M3) to indicate which fields must match.
The MR indicator is set on only if all three match fields in either of the files
EMPMAS and DEPTMS are the same as all three fields from the WEEKRC file.
The three match fields in each file are combined and treated as one match field
organized in the following descending sequence:
DIVSON
M3
DEPT
M2
EMPLNO M1
The order in which the match fields are specified in the input specifications does
not affect the organization of the match fields.
102
ILE RPG for AS/400 Reference
Primary/Secondary Multi-file Processing
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................
I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr....
IDISK
AB 01
1 C1
I
OR
02
1 C2
I
OR
03
1 C3
I
1
10 0EMPNO
M1
I
11
15 0DUMMY
M2
I
11
15 0DEPT
M202
I
16
20 0DEPT
M203
M 1
E M P N O
Record Identifying Indicator 01
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
M 1
E M P N O
M 2
D E P T
Record Identifying Indicator 02
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
M 1
E M P N O
M 2
D E P T
Record Identifying Indicator 03
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
Figure 42. Match Fields with a Dummy M2 Field
Three different record types are found in the input file. All three contain a match
field in positions 1 through 10. Two of them have a second match field. Because
M1 is found on all record types, it can be specified without a field record relation
entry in positions 67 and 68. If one match value (M1 through M9) is specified
without field record relation entries, all match values must be specified once without
field record relation entries. Because the value M1 is specified without field record
relationship, an M2 value must also be specified once without field record relationship. The M2 field is not on all record types; therefore a dummy M2 field must be
specified next. The dummy field can be given any unique name, but its specified
length must be equal to the length of the true M2 field. The M2 field is then related
to the record types on which it is found by field record relation entries.
Chapter 7. General File Considerations
103
Primary/Secondary Multi-file Processing
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++
FPRIMARY
IPEA F
64
DISK
FFIRSTSEC IS A F
64
DISK
FSECSEC
IS A F
64
DISK
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................
I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr....
IPRIMARY
AA 01
1 CP
2NC
I
2
3 MATCH
M1
*
I
BB 02
1 CP
2 C
I
2
3 NOM
*
IFIRSTSEC AB 03
1 CS
2NC
I
2
3 MATCH
M1
*
I
BC 04
1 CS
2 C
I
2
3 NOM
*
ISECSEC
AC 05
1 CT
2NC
I
2
3 MATCH
M1
*
I
BD 06
1 CT
2 C
I
2
3 NOM
Figure 43. Match Field Specifications for Three Disk Files
Processing Matching Records
Matching records for two or more files are processed in the following manner:
¹ Whenever a record from the primary file matches a record from the secondary
file, the primary file is processed first. Then the matching secondary file is processed. The record identifying indicator that identifies the record type just
selected is on at the time the record is processed. This indicator is often used
to control the type of processing that takes place.
¹ Whenever records from ascending files do not match, the record having the
lowest match field content is processed first. Whenever records from
descending files do not match, the record having the highest match field
content is processed first.
¹ A record type that has no match field specification is processed immediately
after the record it follows. The MR indicator is off. If this record type is first in
the file, it is processed first even if it is not in the primary file.
¹ The matching of records makes it possible to enter data from primary records
into their matching secondary records because the primary record is processed
before the matching secondary record. However, the transfer of data from secondary records to matching primary records can be done only when look-ahead
fields are specified.
Figure 44 on page 105 through Figure 45 on page 106 show how records from
three files are selected for processing.
104
ILE RPG for AS/400 Reference
Primary/Secondary Multi-file Processing
P
P
P
P
P
P
P
P
P
20
20
40
50
11 12 13 17 22
Primary File
No Match Field
60 80
1
2
5
6
S
S
S
S
S
20
30
30
60
3
7
8
9
T
T
T
T
10
30
50
50
4
10 14 15 16 20 25 26
S
S
S
S
70
80
80
First Secondary File
Match Field
18 19 21 23 24
T
T
T
T
60
80
80
Second Secondary File
The records from the three disk files above are selected in the order
indicated by the dark numbers.
Figure 44. Normal Record Selection from Three Disk Files
Table 10 (Page 1 of 2). Normal Record Selection from Three Disk Files
Cycle
File Processed
Indicators On
Reason for Setting Indicator
1
PRIMARY
02
No match field specified
2
PRIMARY
02
No match field specified
3
FIRSTSEC
04
No match field specified
4
SECSEC
05
Second secondary low; no primary match
5
PRIMARY
01, MR
Primary matches first secondary
6
PRIMARY
01, MR
Primary matches first secondary
7
FIRSTSEC
03, MR
First secondary matches primary
8
FIRSTSEC
03
First secondary low; no primary match
9
FIRSTSEC
03
First secondary low; no primary match
10
SECSEC
05
Second secondary low; no primary match
11
PRIMARY
01
Primary low; no secondary match
12
PRIMARY
01, MR
Primary matches second secondary
13
PRIMARY
02
No match field specified
14
SECSEC
05, MR
Second secondary matches primary
15
SECSEC
05, MR
Second secondary matches primary
16
SECSEC
06
No match field specified
17
PRIMARY
01, MR
Primary matches both secondary files
18
FIRSTSEC
03, MR
First secondary matches primary
19
FIRSTSEC
04
No match field specified
20
SECSEC
05, MR
Second secondary matches primary
21
FIRSTSEC
03
First secondary low; no primary match
Chapter 7. General File Considerations
105
Primary/Secondary Multi-file Processing
Table 10 (Page 2 of 2). Normal Record Selection from Three Disk Files
Cycle
File Processed
Indicators On
Reason for Setting Indicator
22
PRIMARY
01, MR
Primary matches both secondary files
23
FIRSTSEC
03, MR
First secondary matches primary
24
FIRSTSEC
02, MR
First secondary matches primary
25
SECSEC
05, MR
Second secondary matches primary
26
SECSEC
05, MR
Second secondary matches primary
STEP 1
P
S
T 10
The first record from each file is read. The P and S
records have no match field, so they are processed
before the T record that has a match field. Because
the P record comes from the primary file, it is selected
for processing first.
STEP 2
P
S
T 10
The next P record is read. It contains no match field
and comes from the primary file, so the new P record
is also selected for processing before the S record.
STEP 3
P 20
S
T 10
The next P record has a match field. The S record
has no match field, so it is selected for processing.
STEP 4
P 20
S 20
T 10
STEP 5
P 20
S 20
T 30
The next S record is read. All three records have
match fields. Because the value in the match field
of the T record is lower than the value in the other
two, the T record is selected for processing.
The next T record is read. The matching P and S
records both have the low match field value, so
they are processed before the T record. Because
the matching P record comes from the pr imary file,
it is selected for processing first.
Figure 45 (Part 1 of 2). Normal Record Selection from Three Disk Files
106
ILE RPG for AS/400 Reference
File Translation
STEP 6
P 20
S 20
T 30
The next P record is read. Because it contains the
same match field and comes from the pr imary file,
the new P record is selected instead of the S record.
T 30
The next P record is read. The value of the match
field in the S record is the lowest of the three, so the
S record is selected for processing.
STEP 7
P 40
S 20
STEP 8
P 40
S 30
T 30
The next S record is read. Because the S and T
records have the lowest match field, they are
selected before the P record. Because the S record
comes from the first secondar y file, it is selected for
processing before the T record.
STEP 9
P 40
S 30
T 30
The next S record is read. Because it also has
the same match field as the S record just selected,
it too is selected before the T record.
STEP 10
P 40
S 60
T 30
The next S record is read. The T record contains
the lowest match field value, and is selected for
processing.
Figure 45 (Part 2 of 2). Normal Record Selection from Three Disk Files
File Translation
The file translation function translates any of the 8-bit codes used for characters
into another 8-bit code. The use of file translation indicates one or both of the
following:
¹ A character code used in the input data must be translated into the system
code.
¹ The output data must be translated from the system code into a different code.
The translation on input data occurs before any field selection has taken place.
The translation on output data occurs after any editing taken place.
Remember the following when specifying file translation:
¹ File translation can be specified for data in array or table files (T in position 18
of the file description specifications).
Chapter 7. General File Considerations
107
File Translation
¹ File translation can be used with data in combined, input, or update files that
are translated at input and output time according to the file translation table
provided. If file translation is used to translate data in an update file, each
record must be written before the next record is read.
¹ For any I/O operation that specifies a search argument in factor 1 (such as
CHAIN, READE, READPE, SETGT, or SETLL) for files accessed by keys, the
search argument is translated before the file is accessed.
¹ If file translation is specified for both a record address file and the file being
processed (if the file being processed is processed sequentially within limits),
the records in the record address file are first translated according to the file
translation specified for that file, and then the records in the file being processed are translated according to the file translation specified for that file.
¹ File translation applies only on a single byte basis.
¹ Every byte in the input and output record is translated
Specifying File Translation
To specify file translation, use the FTRANS keyword on the control specification.
The translations must be transcribed into the correct record format for entry into the
system. These records, called the file translation table records, must precede any
alternate collating sequence records, or arrays and tables loaded at compile time.
They must be preceded by a record with **Ï (Ï = blank) in positions 1 through 3 or
**FTRANS in positions 1 through 8. The remaining positions in this record can be
used for comments.
Translating One File or All Files
File translation table records must be formatted as follows:
Record
Position
Entry
1-8 (to
translate
all files)
Enter *FILESÏÏ (Ï represents a blank) to indicate that all files are to be translated. Complete the
file translation table record beginning with positions 11 and 12. If *FILESÏÏ is specified, no other
file translation table can be specified in the program.
1-8 (to translate a specific
file)
Enter the name of the file to be translated. Complete the file translation table record beginning
with positions 11 and 12. The *FILESÏÏ entry is not made in positions 1 through 8 when a
specific file is to be translated.
9-10
Blank
11-12
Enter the hexadecimal value of the character to be translated from on input or to be translated
to on output.
13-14
Enter the hexadecimal equivalent of the internal character the RPG IV language works with. It
will replace the character in positions 11 and 12 on input and be replaced by the character in
positions 11 and 12 on output.
15-18
19-22
23-26
...
77-80
All groups of four beginning with position 15 are used in the same manner as positions 11
through 14. In the first two positions of a group, enter the hexadecimal value of the character to
be replaced. In the last two positions, enter the hexadecimal value of the character that
replaces it.
The first blank entry ends the record. There can be one or more records per file
translation table. When multiple records are required in order to define the table,
the same file name must be entered on all records. A change in file name is used
108
ILE RPG for AS/400 Reference
File Translation
to separate multiple translation tables. An *FILES record causes all files, including
tables and arrays specified by a T in position 18 of the file description specifications, to be translated by the same table.
HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* In this example all the files are translated
H FTRANS
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++
FFILE1
IP
F
10
DISK
FFILE2
IS
F
10
DISK
FFILE3
IS
F
10
DISK
FFILE4
IS
F
10
DISK
**FTRANS
*FILES
81C182C283C384C4
HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* In this example different translate tables are used and
* FILE3 is not translated.
H FTRANS
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++
FFILE1
IP
F
10
DISK
FFILE2
IS
F
10
DISK
FFILE3
IS
F
10
DISK
FFILE4
IS
F
10
DISK
**FTRANS
FILE1
8182
FILE2
C1C2
FILE4
81C182C283C384C4
Translating More Than One File
If the same file translation table is needed for more than one file but not for all files,
two types of records must be specified. The first record type specifies the file using
the tables, and the second record type specifies the table. More than one record for
each of these record types can be specified. A change in file names is used to
separate multiple translation tables.
Specifying the Files
File translation table records must be formatted as follows:
Record
Position
Entry
1-7
*EQUATE
8-10
Leave these positions blank.
11-80
Enter the name(s) of file(s) to be translated. If more than one file is to be
translated, the file names must be separated by commas.
Additional file names are associated with the table until a file name not followed by
a comma is encountered. A file name cannot be split between two records; a
comma following a file name must be on the same record as the file name. You
can create only one file translation table by using *EQUATE.
Chapter 7. General File Considerations
109
File Translation
Specifying the Table
File translation table records must be formatted as follows:
Record
Position
Entry
1-7
*EQUATE
8-10
Leave these positions blank.
11-12
Enter the hexadecimal value of the character to be translated from on
input or to be translated to on output.
13-14
Enter the hexadecimal equivalent of the internal character the RPG IV
language works with. It will replace the character in positions 11 and 12
on input and be replaced by the character in positions 11 and 12 on
output.
15-18
19-22
23-26
...
77-80
All groups of four beginning with position 15 are used the same way as
positions 11 through 14. In the first two positions of a group, enter the
hexadecimal value of the character to be replaced. In the last two positions, enter the hexadecimal value of the character that replaces it.
The first blank record position ends the record. If the number of entries exceeds 80
positions, duplicate positions 1 through 10 on the next record and continue as
before with the translation pairs in positions 11 through 80. All table records for one
file must be kept together.
The records that describe the file translation tables must be preceded by a record
with **Ï (Ï = blank) in positions 1 through 3 or with **FTRANS. The remaining positions in this record can be used for comments.
HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* In this example several files are translated with the
* same translation table. FILE2 is not translated.
H FTRANS
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++
FFILE1
IP
F
10
DISK
FFILE2
IS
F
10
DISK
FFILE3
IS
F
10
DISK
FFILE4
IS
F
10
DISK
**FTRANS
*EQUATE
FILE1,FILE3,FILE4
*EQUATE
81C182C283C384C485C586C687C788C889C98ACA8BCB8CCC8DCD8ECE8F
*EQUATE
91D192D2
110
ILE RPG for AS/400 Reference
Definitions
This section provides information on the different types of definitions that can be
coded in your source. It describes:
¹ How to define
– Standalone fields, arrays, and tables
– Named constants
– Data structures and their subfields
– Prototypes
– Prototyped parameters
– Procedure interface
¹ Scope and storage of definitions as well as how to define each definition type.
¹ Data types and Data formats
¹ Editing numeric fields
For information on how to define files, see Chapter 14, “File Description
Specifications” on page 249 and also the chapter on defining files in the ILE RPG
for AS/400 Programmer's Guide.
 Copyright IBM Corp. 1994, 1999
111
112
ILE RPG for AS/400 Reference
General Considerations
Chapter 8. Defining Data and Prototypes
ILE RPG allows you to define the following items:
¹ Data items such as data structures, data-structure subfields, standalone fields,
and named constants. Arrays and tables can be defined as either a datastructure subfield or a standalone field.
¹ Prototypes, procedure interfaces, and prototyped parameters
This chapter presents information on the following topics:
¹ General considerations, including definition types, scope, and storage
¹ Standalone fields
¹ Constants
¹ Data Structures
¹ Prototypes, parameters, and procedure interfaces
General Considerations
You define items by using definition specifications. Definitions can appear in two
places within a module or program: within the main source section and within a
subprocedure. (The main source section consists of the first set of H, F, D, I, C,
and O specifications in a module; it corresponds to the specifications found in a
standalone program or a main procedure.) Depending on where the definition
occurs, there are differences both in what can be defined and also the scope of the
definition. Specify the type of definition in positions 24 through 25, as follows:
Entry
Definition Type
Blank
A data structure subfield or parameter definition
C
Named constant
DS
Data structure
PI
Procedure interface
PR
Prototype
S
Standalone field
Definitions of data structures, prototypes, and procedure interfaces end with the first
definition specification with non-blanks in positions 24-25, or with the first specification that is not a definition specification.
 Copyright IBM Corp. 1994, 1999
113
General Considerations
*-----------------------------------------------------------------*
* Global Definitions
*-----------------------------------------------------------------*
D String
S
6A
INZ('ABCDEF')
D Spcptr
S
*
D SpcSiz
C
8
D DS1
DS
OCCURS(3)
D Fld1
5A
INZ('ABCDE')
D Fld1a
1A
DIM(5) OVERLAY(Fld1)
D Fld2
5B 2 INZ(123.45)
D Switch
PR
D
Parm
1A
...
*-----------------------------------------------------------------*
* Local Definitions
*-----------------------------------------------------------------*
P Switch
B
D Switch
PI
D
Parm
1A
* Define a local variable.
D Local
S
5A
INZ('aaaaa')
...
P
E
Figure 46. Sample Definitions
Scope of Definitions
Depending on where a definition occurs, it will have different scope. Scope refers
to the range of source lines where a name is known. There are two types of
scope: global and local, as shown in Figure 47.
*MODULE
Main
Source
Section
Main Procedure
Global
Scope
Subprocedure 1
Local
Scope
Subprocedure 2
Local
Scope
Program Data - part of main source section
Figure 47. Scope of Definitions
In general, all items that are defined in the main source section are global, and
therefore, known throughout the module. Global definitions are definitions that can
be used by both the main procedure and any subprocedures within the module.
They can also be exported.
114
ILE RPG for AS/400 Reference
General Considerations
Items in a subprocedure, on the other hand, are local. Local definitions are definitions that are known only inside that subprocedure. If an item is defined with the
same name as a global item, then any references to that name inside the subprocedure will use the local definition.
However, note the following exceptions:
¹ Subroutine names and tag names are known only to the procedure in which
they are defined. This includes subroutine or tag names that defined in the
main procedure.
¹ All fields specified on input and output specifications are global. For example, if
a subprocedure does an operation using a record format, say a WRITE operation, the global fields will be used even if there are local definitions with the
same names as the record format fields.
Sometimes you may have a mix of global and local definitions. For example,
KLISTs and PLISTs can be global or local. The fields associated with global
KLISTs and PLISTs contain only global fields. The fields associated with local
KLISTs and PLISTs can contain both global and local fields. For more information
on the behavior of KLISTs and KFLDs inside subprocedures, see “Scope of
Definitions” on page 93.
Storage of Definitions
Local definitions use automatic storage. Automatic storage is storage that exists
only for the duration of the call to the procedure. Variables in automatic storage do
not save their values across calls.
Global definitions, on the other hand, use static storage. Static storage is storage
that has a constant location in memory for all calls of a program or procedure. It
keeps its value across calls.
Specify the STATIC keyword to indicate that a local field definition use static
storage, in which case it will keep its value on each call to the procedure. If the
keyword STATIC is specified, the item will be initialized at module initialization time.
Static storage in the main procedure is subject to the RPG cycle, and so the value
changes on the next call if LR was on at the end of the last call. However, local
static variables will not get reinitialized because of LR in the main procedure.
TIP
Using automatic storage reduces the amount of storage that is required at run
time by the program. The storage is reduced largely because automatic storage
is only allocated while the procedure is running. On the other hand, all static
storage associated with the program is allocated when the program starts, even
if no procedure using the static storage is ever called.
Chapter 8. Defining Data and Prototypes
115
Constants
Standalone Fields
Standalone fields allow you to define individual work fields. A standalone field has
the following characteristics:
¹ It has a specifiable internal data type
¹ It may be defined as an array, table, or field
¹ It is defined in terms of data length, not in terms of absolute byte positions.
For more information on standalone fields, see:
¹ Chapter 9, “Using Arrays and Tables” on page 143
¹ Chapter 10, “Data Types and Data Formats” on page 159
¹ “Definition-Specification Keywords” on page 279
Variable Initialization
You can initialize data with the “INZ{(initial value)}” on page 290 keyword on the
definition specification. Specify an initial value as a parameter on the INZ keyword,
or specify the keyword without a parameter and use the default initial values. If the
initialization is too complicated to express using the INZ keyword, you can further
initialize data in the initialization subroutine.
Default initial values for the various data types are described in Chapter 10, “Data
Types and Data Formats” on page 159. See Chapter 9, “Using Arrays and Tables”
on page 143 for information on initializing arrays.
To reinitialize data while the program is running, use the CLEAR and RESET operations.
The CLEAR operation code sets a record format or variable (field, subfield, indicator, data structure, array, or table) to its default value. All fields in a record
format, data structure, or array are cleared in the order in which they are declared.
The RESET operation code restores a variable to its reset value. The reset value
for a global variable is the value it had at the end of the initialization step in the
RPG IV cycle, after the initialization subroutine has been invoked.
You can use the initialization subroutine to assign initial values to a global variable
and then later use RESET to set the variable back to this value. This applies only
to the initialization subroutine when it is run automatically as a part of the initialization step.
For local variables the reset value is the value of the variable when the subprocedure was first called, but before the calculations begin.
Constants
Literals and named constants are types of constants. They can be specified in any
of the following places:
¹ In factor 1
¹ In factor 2
116
ILE RPG for AS/400 Reference
Constants
¹ In an extended factor 2 on the calculation specifications
¹ As parameters to keywords on the control specification
¹ As parameters to built-in functions
¹ In the Field Name, Constant, or Edit Word fields in the output specifications.
¹ As array indexes
¹ As the format name in a WORKSTN output specification
¹ With keywords on the definition specification.
Literals
A literal is a self-defining constant that can be referred to in a program. A literal can
belong to any of the RPG IV data types.
Character Literals
The following are the rules for specifying a character literal:
¹ Any combination of characters can be used in a character literal. This includes
DBCS characters. DBCS characters must be enclosed by shift-out and shift-in
characters and must be an even number of bytes. Embedded blanks are valid.
¹ A character literal with no characters between the apostrophes is allowed. See
Figure 49 on page 121 for examples.
¹ Character literals must be enclosed in apostrophes (’).
¹ An apostrophe required as part of a literal is represented by two apostrophes.
For example, the literal O’CLOCK is coded as ‘O’’CLOCK’.
¹ Character literals are compatible only with character data.
|
|
¹ Indicator literals are one byte character literals which contain either '1' (on) or
'0' (off).
Hexadecimal Literals
The following are the rules for specifying a hexadecimal literal:
¹ Hexadecimal literals take the form:
X'x1x2...xn'
where X'x1x2...xn' can only contain the characters A-F, a-f, and 0-9.
¹ The literal coded between the apostrophes must be of even length.
¹ Each pair of characters defines a single byte.
¹ Hexadecimal literals are allowed anywhere that character literals are supported
except as factor 2 of ENDSR and as edit words.
¹ Except when used in the bit operations BITON, BITOFF, and TESTB, a
hexadecimal literal has the same meaning as the corresponding character
literal. For the bit operations, factor 2 may contain a hexadecimal literal representing 1 byte. The rules and meaning are the same for hexadecimal literals as
for character fields.
¹ If the hexadecimal literal contains the hexadecimal value for a single quote, it
does not have to be specified twice, unlike character literals. For example, the
Chapter 8. Defining Data and Prototypes
117
Constants
literal A'B is specified as 'A'B' but the hexadecimal version is X'C17DC2' not
X'C17D7DC2'.
¹ Normally, hexadecimal literals are compatible only with character data.
However, a hexadecimal literal that contains 16 or fewer hexadecimal digits can
be treated as an unsigned numeric value when it is used in a numeric
expression or when a numeric variable is initialized using the INZ keyword.
|
|
|
|
Numeric Literals
The following are the rules for specifying a numeric literal:
¹ A numeric literal consists of any combination of the digits 0 through 9. A
decimal point or a sign can be included.
¹ The sign (+ or -), if present, must be the leftmost character. An unsigned literal
is treated as a positive number.
¹ Blanks cannot appear in a numeric literal.
¹ Numeric literals are not enclosed in apostrophes (’).
¹ Numeric literals are used in the same way as a numeric field, except that
values cannot be assigned to numeric literals.
¹ The decimal separator may be either a comma or a period
Numeric literals of the float format are specified differently. Float literals take the
form:
<mantissa>E<exponent>
Where
<mantissa> is a literal as described above with 1 to 16 digits
<exponent> is a literal with no decimal places, with a value
between -308 and +308
¹ Float literals do not have to be normalized. That is, the mantissa does not have
to be written with exactly one digit to the left of the decimal point. (The decimal
point does not even have to be specified.)
¹ Lower case e may be used instead of E.
¹ Either a period ('.') or a comma (',') may be used as the decimal point.
¹ Float literals are allowed anywhere that numeric constants are allowed except
in operations that do not allow float data type. For example, float literals are not
allowed in places where a numeric literal with zero decimal positions is
expected, such as an array index.
¹ Float literals follow the same continuation rules as for regular numeric literals.
The literal may be split at any point within the literal.
¹ A float literal must have a value within the limits described in 1.6.2, "Rules for
Defining" on page 4.
The following lists some examples of valid float literals:
1E1
1.2e-1
-1234.9E0
12e12
+67,89E+0003
118
ILE RPG for AS/400 Reference
=
=
=
=
=
10
.12
-1234.9
12000000000000
67890 (the comma is the decimal point)
Constants
The following lists some examples of invalid float literals:
1.234E
1.2e-1234.9E+309
12E-2345
1.797693134862316e308
179.7693134862316E306
0.0000000001E-308
<--<--<--<--<--<--<---
no exponent
no exponent
exponent too big
exponent too small
value too big
value too big
value too small
Date Literals
Date literals take the form D'xx-xx-xx' where:
¹ D indicates that the literal is of type date
¹ xx-xx-xx is a valid date in the format specified on the control specification (separator included)
¹ xx-xx-xx is enclosed by apostrophes
Time Literals
Time literals take the form T'xx:xx:xx' where:
¹ T indicates that the literal is of type time
¹ xx:xx:xx is a valid time in the format specified on the control specification (separator included)
¹ xx:xx:xx is enclosed by apostrophes
Timestamp Literals
Timestamp literals take the form Z'yyyy-mm-dd-hh.mm.ss.mmmmmm' where:
¹ Z indicates that the literal is of type timestamp
¹ yyyy-mm-dd is a valid date (year-month-day)
¹ hh.mm.ss.mmmmmm is a valid time (hours.minutes.seconds.microseconds)
¹ yyyy-mm-dd-hh.mm.ss.mmmmmm is enclosed by apostrophes
¹ Microseconds are optional and if not specified will default to zeros
Graphic Literals
Graphic literals take the form G'oK1K2i' where:
¹ G indicates that the literal is of type graphic
¹ o is a shift-out character
¹ K1K2 is an even number of bytes (possibly zero) and does not contain a
shift-out or shift-in character
¹ i is a shift-in character
¹ oK1K2i is enclosed by apostrophes
|
UCS-2 Literals
|
UCS-2 literals take the form U'Xxxx...Yyyy' where:
|
¹ U indicates that the literal is of type UCS-2.
Chapter 8. Defining Data and Prototypes
119
Constants
|
|
¹ Each UCS-2 literal requires four bytes per UCS-2 character in the literal. Each
four bytes of the literal represents one double-byte UCS-2 character.
|
¹ UCS-2 literals are compatible only with UCS-2 data.
|
UCS-2 literals are assumed to be in the default UCS-2 CCSID of the module.
Example of Defining Literals
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
H DATFMT(*ISO)
* Examples of literals used to initialize fields
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
D DateField
S
D
INZ(D'1988-09-03')
D NumField
S
5P 1 INZ(5.2)
D CharField
S
10A
INZ('abcdefghij')
D UCS2Field
S
2C
INZ(U'00610062')
* Even though the date field is defined with a 2-digit year, the
* initialization value must be defined with a 4-digit year, since
* all literals must be specified in date format specified
* on the control specification.
D YmdDate
S
D
INZ(D'2001-01-13')
D
DATFMT(*YMD)
* Examples of literals used to define named constants
D DateConst
C
CONST(D'1988-09-03')
D NumConst
C
CONST(5.2)
D CharConst
C
CONST('abcdefghij')
|
* Note that the CONST keyword is not required.
D Upper
C
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
* Note that the literal may be continued on the next line
D Lower
C
'abcdefghijklmnD
opqrstuvwxyz'
* Examples of literals used in operations
EVAL
CharField = 'abc'
IF
NumField > 12
EVAL
DateField = D'1995-12-25'
ENDIF
C
C
C
C
Figure 48. Defining named constants
Example of Using Literals with Zero Length
120
ILE RPG for AS/400 Reference
Constants
|
|
|
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
* The following two definitions are equivalent:
D varfld1
S
5
INZ VARYING
D varfld2
S
5
INZ('') VARYING
* Various fields used by the examples below:
D blanks
S
10
INZ
D vblanks
S
10
INZ('
') VARYING
D fixfld1
S
5
INZ('abcde')
* VGRAPHIC and VUCS2 are initialized with zero-length literals.
D vgraphic
S
10G
INZ(G'oi') VARYING
D vucs2
S
10C
INZ(U'') VARYING
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq++++
* The following statements do the same thing:
C
eval
varfld1 = ''
C
clear
varfld1
* Moving '' to a variable-length field using MOVE(P) or MOVEL(P)
* sets the field to blanks up to the fields current length.
C
move(p)
''
varfld1
C
movel(p) ''
varfld1
* Moving '' to a fixed-length field has no effect in the following
* examples: (The rightmost or leftmost 0 characters are changed.)
C
move
''
fixfld1
C
movel
''
fixfld1
* The following comparisons demonstrate how the shorter operand
* is padded with blanks:
C
eval
*in01 = (blanks = '')
* *in01 is '1'
C
eval
*in02 = (vblanks = '')
eval
*in03 = (varfld2 = blanks)
eval
*in04 = (varfld2 = vblanks)
eval
*in05 = (%len(vgraphic)=0)
eval
*in06 = (%len(vucs2)=0)
* *in02 is '1'
C
* *in03 is '1'
C
* *in04 is '1'
C
* *in05 is '1'
|
C
* *in06 is '1'
Figure 49. Character, Graphic, and UCS-2 Literals with Zero Length
Named Constants
You can give a name to a constant. This name represents a specific value which
cannot be changed when the program is running. Numeric named constants have
no predefined precision. Their actual precision is defined by the context that is
specified.
See Figure 48 on page 120 for examples of defining named constants. The value
of the named constant is specified in the keyword section of the definition specification. The presence of the keyword CONST is optional, however. For example, to
Chapter 8. Defining Data and Prototypes
121
Constants
assign a value of 'ab' to a constant, you could specify either CONST('ab') or 'ab' in
the keyword section.
Figurative Constants
The figurative constants *BLANK/*BLANKS, *ZERO/*ZEROS, *HIVAL, *LOVAL,
*NULL, *ALL'x..', *ALLG'oK1K2i', *ALLU'XxxxYyyy', *ALLX'x1..', and *ON/*OFF are
implied literals that can be specified without a length, because the implied length
and decimal positions of a figurative constant are the same as those of the associated field. (For exceptions, see the following section, “Rules for Figurative
Constants” on page 123.)
|
Figurative constants can be specified in factor 1 and factor 2 of the calculation
specifications. The following shows the reserved words and implied values for figurative constants:
Reserved Words Implied Values
|
|
|
*BLANK/*BLANKS
All blanks. Valid only for character, graphic, or UCS-2 fields. The value
for character is ' ' (blank) or X'40', for graphic is X'4040', and for
UCS-2 is X'0020'.
|
|
*ZERO/*ZEROS
Character/numeric fields: All zeros. The value is '0' or X'F0'. For
numeric float fields: The value is '0 E0'.
|
*HIVAL
Character, graphic, or UCS-2 fields: The highest collating character
for the system (hexadecimal FFs). Numeric fields: The maximum value
allowed for the corresponding field (with a positive sign if applicable).
For Float fields: *HIVAL for 4-byte float = 3.402 823 5E38
(x'FF7FFFFF') *HIVAL for 8-byte float = 1.797 693 134 862 315 E308
(x'FFEFFFFFFFFFFFFF') Date, time and timestamp fields: See “Date
Data Type” on page 185, “Time Data Type” on page 188 and
“Timestamp Data Type” on page 190 for *HIVAL values for date, time,
and timestamp data.
|
*LOVAL
Character, graphic, or UCS-2 fields: The lowest collating character
for the system (hexadecimal zeros). Numeric fields: The minimum
value allowed (with a negative sign if applicable). For Float fields:
*LOVAL for 4-byte float = -3.402 823 5E38 (x'7F7FFFFF') *LOVAL for
8-byte float = -1.797 693 134 862 315 E308 (x'7FEFFFFFFFFFFFFF')
Date, time and timestamp fields: See “Date Data Type” on page 185,
“Time Data Type” on page 188 and “Timestamp Data Type” on
page 190 for *LOVAL values for date, time, and timestamp data.
*ALL'x..'
Character/numeric fields: Character string x . . is cyclically repeated to
a length equal to the associated field. If the field is a numeric field, all
characters within the string must be numeric (0 through 9). No sign or
decimal point can be specified when *ALL'x..' is used as a numeric constant.
Note: You cannot use *ALL'x..' with numeric fields of float format.
Note: For numeric integer or unsigned fields, the value is never greater
than the maximum value allowed for the corresponding field. For
example, *ALL'95' represents the value 9595 if the corresponding field is a 5-digit integer field, since 95959 is greater
than the maximum value allowed for a 5-digit signed integer.
122
ILE RPG for AS/400 Reference
Constants
*ALLG'oK1K2i'
Graphic fields: The graphic string K1K2 is cyclically repeated to a
length equal to the associated field.
|
|
|
|
|
|
|
*ALLU'XxxxYyyy'
UCS-2 fields: A figurative constant of the form *ALLU'XxxxYyyy' indicates a literal of the form 'XxxxYyyyXxxxYyyy...' with a length determined by the length of the field associated with the *ALLU'XxxxYyyy'
constant. Each double-byte character in the constant is represented by
four hexadecimal digits. For example, *ALLU'0041' represents a string of
repeated UCS-2 'A's.
*ALLX'x1..'
Character fields: The hexadecimal literal X'x1..' is cyclically repeated to
a length equal to the associated field.
*NULL
A null value valid for basing pointers or procedure pointers
*ON/*OFF
|
|
*ON is all ones ('1' or X'F1'). *OFF is all zeros ('0' or X'F0'). Both are
only valid for character fields.
Rules for Figurative Constants
Remember the following rules when using figurative constants:
¹ MOVE and MOVEL operations allow you to move a character figurative constant to a numeric field. The figurative constant is first expanded as a zoned
numeric with the size of the numeric field, then converted to packed or binary
numeric if needed, and then stored in the target numeric field. The digit portion
of each character in the constant must be valid. If not, a decimal data error will
occur.
¹ Figurative constants are considered elementary items. Except for MOVEA, figurative constants act like a field if used in conjunction with an array. For
example: MOVE *ALL'XYZ' ARR.
If ARR has 4-byte character elements, then each element will contain 'XYZX'.
¹ MOVEA is considered to be a special case. The constant is generated with a
length equal to the portion of the array specified. For example:
– MOVEA *BLANK ARR(X)
Beginning with element X, the remainder of ARR will contain blanks.
– MOVEA *ALL'XYZ' ARR(X)
ARR has 4-byte character elements. Element boundaries are ignored, as is
always the case with character MOVEA operations. Beginning with element
X, the remainder of the array will contain 'XYZXYZXYZ...'.
Note that the results of MOVEA are different from those of the MOVE example
above.
¹ After figurative constants are set/reset to their appropriate length, their normal
collating sequence can be altered if an alternate collating sequence is specified.
¹ The move operations MOVE and MOVEL produce the same result when
moving the figurative constants *ALL'x..', *ALLG'oK1K2i', and *ALLX'x1..'. The
Chapter 8. Defining Data and Prototypes
123
Data Structures
string is cyclically repeated character by character (starting on the left) until the
length of the associated field is the same as the length of the string.
¹ Figurative constants can be used in compare operations as long as one of the
factors is not a figurative constant.
¹ The figurative constants, *BLANK/*BLANKS, are moved as zeros to a numeric
field in a MOVE operation.
Data Structures
The ILE RPG compiler allows you to define an area in storage and the layout of the
fields, called subfields, within the area. This area in storage is called a data structure. You define a data structure by specifying DS in positions 24 through 25 on a
definition specification.
You can use a data structure to:
¹ Define the same internal area multiple times using different data formats
¹ Define a data structure and its subfields in the same way a record is defined.
¹ Define multiple occurrences of a set of data.
¹ Group non-contiguous data into contiguous internal storage locations.
¹ Operate on all the subfields as a group using the name of the data structure.
¹ Operate on an individual subfield using its name.
In addition, there are four special data structures, each with a specific purpose:
¹ A data area data structure (identified by a U in position 23 of the definition
specification)
¹ A file information data structure (identified by the keyword INFDS on a file
description specification)
¹ A program-status data structure (identified by an S in position 23 of the definition specification)
¹ An indicator data structure (identified by the keyword INDDS on a file
description specification).
Data structures can be either program-described or externally described, except for
indicator data structures, which are program-described only.
A program-described data structure is identified by a blank in position 22 of the
definition specification. The subfield definitions for a program-described data structure must immediately follow the data structure definition.
An externally described data structure, identified by an E in position 22 of the definition specification, has subfield descriptions contained in an externally described
file. At compile time, the ILE RPG compiler uses the external name to locate and
extract the external description of the data structure subfields. You specify the
name of the external file either in positions 7 through 21, or as a parameter for the
keyword EXTNAME.
Note: The data formats specified for the subfields in the external description are
used as the internal formats of the subfields by the compiler. This differs
from the way in which externally described files are treated.
124
ILE RPG for AS/400 Reference
Data Structures
An external subfield name can be renamed in the program using the keyword
EXTFLD. The keyword PREFIX can be used to add a prefix to the external subfield
names that have not been renamed with EXTFLD. Note that the data structure subfields are not affected by the PREFIX keyword specified on a file-description specification even if the file name is the same as the parameter specified in the
EXTNAME keyword when defining the data structure using an external file name.
Additional subfields can be added to an externally described data structure by
specifying program-described subfields immediately after the list of external subfields.
Defining Data Structure Subfields
You define a subfield by specifying blanks in the Definition-Type entry (positions 24
through 25) of a definition specification. The subfield definition(s) must immediately
follow the data structure definition. The subfield definitions end when a definition
specification with a non-blank Definition-Type entry is encountered, or when a different specification type is encountered.
The name of the subfield is entered in positions 7 through 21. To improve readability of your source, you may want to indent the subfield names to show visually
that they are subfields.
You can also define a subfield like an existing item using the LIKE keyword. When
defined in this way, the subfield receives the length and data type of the item on
which it is based. See Figure 107 on page 292 for an example using the LIKE
keyword.
You can overlay the storage of a previously defined subfield with that of another
subfield using the OVERLAY keyword. The keyword is specified on the later subfield definition. See Figure 53 on page 131 for an example using the OVERLAY
keyword.
Specifying Subfield Length
The length of a subfield may be specified using absolute (positional) or length notation.
Absolute Specify a value in both the From-Position (positions 26 through 32) and
the To-Position/Length (positions 33 through 39) entries on the definition
specification.
Length
Specify a value in the To-Position/Length (positions 33 through 39)
entry. The From-Position entry is blank.
When using length notation, the subfield is positioned such that its starting position
is greater than the maximum To-Position of all previously defined subfields. For
examples of each notation, see “Data Structure Examples” on page 128.
Aligning Data Structure Subfields
Alignment of subfields may be necessary. In some cases it is done automatically; in
others, it must be done manually.
For example, when defining subfields of type basing pointer or procedure pointer
using the length notation, the compiler will automatically perform padding if necessary to ensure that the subfield is aligned properly.
Chapter 8. Defining Data and Prototypes
125
Data Structures
When defining float, integer or unsigned subfields, alignment may be desired to
improve run-time performance. If the subfields are defined using length notation,
you can automatically align float, integer or unsigned subfields by specifying the
keyword ALIGN on the data structure definition. However, note the following
exceptions:
¹ The ALIGN keyword is not allowed for a file information data structure or a
program status data structure.
¹ Subfields defined using the keyword OVERLAY are not aligned automatically,
even if the keyword ALIGN is specified for the data structure. In this case, you
must align the subfields manually.
Automatic alignment will align the fields on the following boundaries.
¹ 2 bytes for 5-digit integer or unsigned subfields
|
¹ 4 bytes for 10-digit integer or unsigned subfields or 4-byte float subfields
¹ 8 bytes for 20-digit integer or unsigned subfields
|
¹ 8 bytes for 8-byte float subfields
¹ 16 bytes for pointer subfields
If you are aligning fields manually, make sure that they are aligned on the same
boundaries. A start-position is on an n-byte boundary if ((position - 1)mod n) =
0. (The value of "x mod y" is the remainder after dividing x by y in integer arithmetic. It is the same as the MVR value after X DIV Y.)
Figure 50 shows a sequence of bytes and identifies the different boundaries used
for alignment.
Figure 50. Boundaries for Data Alignment
Note the following about the above byte sequence:
¹ Position 1 is on a 16-byte boundary, since ((1-1) mod 16) = 0.
¹ Position 13 is on a 4-byte boundary, since ((13-1) mod 4) = 0.
¹ Position 7 is not on a 4-byte boundary, since ((7-1) mod 4) = 2.
Special Data Structures
Special data structures include:
¹ Data area data structures
¹ File information data structures (INFDS)
¹ Program-status data structures
¹ Indicator data structures.
Note that the above data structures cannot be defined in subprocedures.
126
ILE RPG for AS/400 Reference
Data Structures
Data Area Data Structure
A data area data structure, identified by a U in position 23 of the definition specification, indicates to the compiler that it should read in and lock the data area of the
same name at program initialization and should write out and unlock the same data
area at the end of the program. Locking does not apply to the local data area (see
“Local Data Area (*LDA)”). Data area data structures, as in all other data structures,
have the type character. A data area read into a data area data structure must also
be character. The data area and data area data structure must have the same
name unless you rename the data area within the ILE RPG program by using the
*DTAARA DEFINE operation code or the DTAARA keyword.
You can specify the data area operations (IN, OUT, and UNLOCK) for a data area
that is implicitly read in and written out. Before you use a data area data structure
with these operations, you must specify that data area data structure name in the
result field of the *DTAARA DEFINE operation or with the DTAARA keyword.
A data area data structure cannot be specified in the result field of a PARM operation in the *ENTRY PLIST.
Local Data Area (*LDA): If you specify blanks for the data area data structure
(positions 7 through 21 of the definition specification that contains a U in position
23), the compiler uses the local data area. To provide a name for the local data
area, use the *DTAARA DEFINE operation, with *LDA in factor 2 and the name in
the result field or DTAARA(*LDA) on the definition specification.
File Information Data Structure
You can specify a file information data structure (defined by the keyword INFDS on
a file description specifications) for each file in the program. This provides you with
status information on the file exception/error that occurred. The file information data
structure name must be unique for each file. A file information data structure contains predefined subfields that provide information on the file exception/error that
occurred. For a discussion of file information data structures and their subfields,
see “File Information Data Structure” on page 65.
Program-Status Data Structure
A program-status data structure, identified by an S in position 23 of the definition
specification, provides program exception/error information to the program. For a
discussion of program-status data structures and their predefined subfields, see
“Program Status Data Structure” on page 82.
Indicator Data Structure
An indicator data structure is identified by the keyword INDDS on the file
description specifications. It is used to store conditioning and response indicators
passed to and from data management for a file. By default, the indicator data structure is initialized to all zeros ('0's).
The rules for defining the data structure are:
¹ It must not be externally described.
¹ It can only have fields of indicator format.
¹ It can be defined as a multiple occurrence data structure.
Chapter 8. Defining Data and Prototypes
127
Data Structures
¹ %SIZE for the data structure will return 99. For a multiple occurrence data
structure, %SIZE(ds:*ALL) will return a multiple of 99. If a length is specified, it
must be 99.
¹ Subfields may contain arrays of indicators as long as the total length does not
exceed 99.
Data Structure Examples
The following examples show various uses for data structures and how to define
them.
128
Example
Description
Figure 51 on page 129
Using a data structure to subdivide a field
Figure 52 on page 130
Using a data structure to group fields
Figure 53 on page 131
Data structure with absolute and length notation
Figure 54 on page 131
Rename and initialize an externally described data structure
Figure 55 on page 132
Using PREFIX to rename all fields in an external data
structure
Figure 56 on page 132
Defining a multiple occurrence data structure
Figure 57 on page 133
Aligning data structure subfields
Figure 58 on page 134
Defining a *LDA data area data structure
Figure 59 on page 135
Using data area data structures (1)
Figure 60 on page 135
Using data area data structures (2)
Figure 61 on page 136
Using an indicator data structure
Figure 62 on page 137
Using a multiple-occurrence indicator data structure
ILE RPG for AS/400 Reference
Data Structures
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
*
* Use length notation to define the data structure subfields.
* You can refer to the entire data structure by using Partno, or by
* using the individual subfields Manufactr, Drug, Strength or Count.
*
D Partno
DS
D Manufactr
4
D Drug
6
D Strength
3
D Count
3 0
D
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC..................................
I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr......
*
* Records in program described file FILEIN contain a field, Partno,
* which needs to be subdivided for processing in this program.
* To achieve this, the field Partno is described as a data structure
* using the above Definition specification
*
IFILEIN
NS 01
1 CA
2 CB
I
3
18 Partno
I
19
29 Name
I
30
40 Patno
Figure 51. Using a Data structure to subdivide a field
Chapter 8. Defining Data and Prototypes
129
Data Structures
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
*
* When you use a data structure to group fields, fields from
* non-adjacent locations on the input record can be made to occupy
* adjacent internal locations. The area can then be referred to by
* the data structure name or individual subfield name.
*
D Partkey
DS
D Location
4
D Partno
8
D Type
4
D
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC..................................
I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr......
*
* Fields from program described file TRANSACTN need to be
* compared to the field retrieved from an Item_Master file
*
ITRANSACTN NS 01
1 C1
2 C2
I
3
10 Partno
I
11
16 0Quantity
I
17
20 Type
I
21
21 Code
I
22
25 Location
I
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* Use the data structure name Partkey, to compare to the field
* Item_Nbr
*
C
:
C
Partkey
IFEQ
Item_Nbr
99
C
:C*
Figure 52. Using a data structure to group fields
130
ILE RPG for AS/400 Reference
Data Structures
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
*
* Define a program described data structure called FRED
* The data structure is composed of 5 fields:
*
1.
An array with element length 10 and dimension 70(Field1)
*
2.
A field of length 30 (Field2)
*
3/4. Divide Field2 in 2 equal length fields (Field3 and Field4)
*
5.
Define a binary field over the 3rd field
* Note the indentation to improve readability
*
*
* Absolute notation:
*
* The compiler will determine the array element length (Field1)
* by dividing the total length (700) by the dimension (70)
*
D FRED
DS
D Field1
1
700
DIM(70)
D Field2
701
730
D
Field3
701
715
D
Field5
701
704B 2
D
Field4
716
730
*
* Length notation:
*
* The OVERLAY keyword is used to subdivide Field2
*
D FRED
DS
D Field1
10
DIM(70)
D Field2
30
D
Field3
15
OVERLAY(Field2)
D
Field5
4B 2 OVERLAY(Field3)
D
Field4
15
OVERLAY(Field2:16)
Figure 53. Data structure with absolute and length notation
|
|
|
|
|
|
|
|
|
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
*
* Define an externally described data structure with internal name
* FRED and external name EXTDS and rename field CUST to CUSTNAME
* Initialize CUSTNAME to 'GEORGE' and PRICE to 1234.89.
* Assign to subfield ITMARR the DIM keyword.
* The ITMARR subfield is defined in the external description as a
* 100 byte character field. This divides the 100 byte character
* field into 10 array elements, each 10 bytes long.
* Using the DIM keyword on an externally described numeric subfield
* should be done with caution, because it will divide the field into
* array elements (similar to the way it does when absolute notation
* is used for program described subfields).
*
D Fred
E DS
EXTNAME(EXTDS)
D
CUSTNAME
E
EXTFLD(CUST) INZ('GEORGE')
D
PRICE
E
INZ(1234.89)
D
ITMARR
E
DIM(10)
Figure 54. Rename and initialize an externally described data structure
Chapter 8. Defining Data and Prototypes
131
Data Structures
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
D
D extds1
E DS
EXTNAME (CUSTDATA)
D
PREFIX (CU_)
D
Name
E
INZ ('Joe's Garage')
D
Custnum
E
EXTFLD (NUMBER)
D
*
* The previous data structure will expand as follows:
* -- All externally described fields are included in the data
*
structure
* -- Renamed subfields keep their new names
* -- Subfields that are not renamed are prefixed with the
*
prefix string
*
* Expanded data structure:
*
D EXTDS1
E DS
D
CU_NAME
E
20A
EXTFLD (NAME)
D
INZ ('Joe's Garage')
D
CU_ADDR
E
50A
EXTFLD (ADDR)
D
CUSTNUM
E
9S0 EXTFLD (NUMBER)
D
CU_SALESMN E
7P0 EXTFLD (SALESMN)
Figure 55. Using PREFIX to rename all fields in an external data structure
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
*
* Define a Multiple Occurrence data structure of 20 elements with:
* -- 3 fields of character 20
* -- A 4th field of character 10 which overlaps the 2nd
*
field starting at the second position.
*
* Named constant 'Max_Occur' is used to define the number of
* occurrences.
*
* Absolute notation (using begin/end positions)
*
D Max_Occur
C
CONST(20)
D
DDataStruct
DS
OCCURS (Max_Occur)
D field1
1
20
D field2
21
40
D field21
22
31
D field3
41
60
*
* Mixture of absolute and length notation
*
D DataStruct
DS
OCCURS(twenty)
D field1
20
D field2
20
D
field21
22
31
D field3
41
60
Figure 56. Defining a multiple occurrence data structure
132
ILE RPG for AS/400 Reference
Data Structures
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
* Data structure with alignment:
D MyDS
DS
ALIGN
* Properly aligned subfields
*
Integer subfields using absolute notation.
D
Subf1
33
34I 0
D
Subf2
37
40I 0
*
Integer subfields using length notation.
*
Note that Subf3 will go directly after Subf2
*
since positions 41-42 are on a 2-byte boundary.
*
However, Subf4 must be placed in positions 45-48
*
which is the next 4-byte boundary after 42.
D
Subf3
5I 0
D
Subf4
10I 0
*
Integer subfields using OVERLAY.
D
Group
101
120A
D
Subf6
5I 0 OVERLAY (Group: 3)
D
Subf7
10I 0 OVERLAY (Group: 5)
D
Subf8
5U 0 OVERLAY (Group: 9)
* Subfields that are not properly aligned:
*
Integer subfields using absolute notation:
D
SubfX1
10
11I 0
D
SubfX2
15
18I 0
*
Integer subfields using OVERLAY:
D
BadGroup
101
120A
D
SubfX3
5I 0 OVERLAY (BadGroup: 2)
D
SubfX4
10I 0 OVERLAY (BadGroup: 6)
D
SubfX5
10U 0 OVERLAY (BadGroup: 11)
*
Integer subfields using OVERLAY:
D
WorseGroup
200
299A
D
SubfX6
5I 0 OVERLAY (WorseGroup)
D
SubfX7
10I 0 OVERLAY (WorseGroup: 3)
*
* The subfields receive warning messages for the following reasons:
* SubfX1 - end position (11) is not a multiple of 2 for a 2 byte field.
* SubfX2 - end position (18) is not a multiple of 4 for a 4 byte field.
* SubfX3 - end position (103) is not a multiple of 2.
* SubfX4 - end position (109) is not a multiple of 4.
* SubfX5 - end position (114) is not a multiple of 4.
* SubfX6 - end position (201) is not a multiple of 2.
* SubfX7 - end position (205) is not a multiple of 4.
Figure 57. Aligning Data Structure Subfields
Chapter 8. Defining Data and Prototypes
133
Data Structures
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
*
* Define a data area data structure based on the *LDA.
*
* Example 1:
* A data area data structure with no name is based on the *LDA.
* In this case, the DTAARA keyword does not have to be used.
*
D
UDS
D SUBFLD
1
600A
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
* Example 2:
* This data structure is explicitly based on the *LDA using
* the DTAARA keyword. Since it is not a data area data
* structure, it must be handled using IN and OUT operations.
*
D LDA_DS
DS
DTAARA(*LDA)
D SUBFLD
1
600A
...
C
IN
LDA_DS
C
OUT
LDA_DS
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
* Example 3:
* This data structure is explicitly based on the *LDA using
* the DTAARA keyword. Since it is a data area data
* structure, it is read in during initialization and written
* out during termination. It can also be handled using IN
* and OUT operations, since the DTAARA keyword was used.
*
D LDA_DS
UDS
DTAARA(*LDA)
D SUBFLD
1
600A
...
C
IN
LDA_DS
C
OUT
LDA_DS
Figure 58. Defining a *LDA data area data structure
134
ILE RPG for AS/400 Reference
Data Structures
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
H DFTNAME(Program1)
H
*
FFilename++IPEASF.....L.....A.Device+.Keywords+++++++++++++++++++++++++++
FSALESDTA IF
E
DISK
*
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
*
* This program uses a data area data structure to accumulate
* a series of totals. The data area subfields are then added
* to fields from the file SALESDTA.
D Totals
UDS
D
Tot_amount
8 2
D
Tot_gross
10 2
D
Tot_net
10 2
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
CL0N01Factor1+++++++Opcode(E)+Factor2++++++++++++++++++++++++++++++++++++++
*
C
:
C
EVAL
Tot_amount = Tot_amount + amount
C
EVAL
Tot_gross = Tot_gross + gross
C
EVAL
Tot_net
= Tot_net
+ net
Figure 59. Using data area data structures (program 1)
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
H DFTNAME(Program2)
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
*
* This program processes the totals accumulated in Program1.
* Program2 then uses the total in the subfields to do calculations.
*
D Totals
UDS
D
Tot_amount
8 2
D
Tot_gross
10 2
D
Tot_net
10 2
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
C
:
C
EVAL
*IN91 = (Amount2 <> Tot_amount)
C
EVAL
*IN92 = (Gross2 <> Tot_gross)
C
EVAL
*IN93 = (Net2
<> Tot_net)
C
:
Figure 60. Using data area data structures (program 2)
Chapter 8. Defining Data and Prototypes
135
Data Structures
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
FFilename++IPEASFRLen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++
* Indicator data structure "DispInds" is associated to file "Disp".
FDisp
CF
E
WORKSTN INDDS (DispInds)
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
*
* This is the indicator data structure:
*
D DispInds
DS
* Conditioning indicators for format "Query"
D
ShowName
21
21N
* Response indicators for format "Query"
D
Exit
3
3N
D
Return
12
12N
D
BlankNum
31
31N
* Conditioning indicators for format "DispSflCtl"
D
SFLDSPCTL
41
41N
D
SFLDSP
42
42N
D
SFLEND
43
43N
D
SFLCLR
44
44N
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* Set indicators to display the subfile:
C
EVAL
SFLDSP = *ON
C
EVAL
SFLEND = *OFF
C
EVAL
SFLCLR = *OFF
C
EXFMT
DispSFLCTL
*
* Using indicator variables, we can write more readable programs:
C
EXFMT
Query
C
IF
Exit or Return
C
RETURN
C
ENDIF
Figure 61. Using an indicator data structure
136
ILE RPG for AS/400 Reference
Data Structures
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
FFilename++IPEASFRLen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++
* Indicator data structure "ErrorInds" is associated to file "Disp".
FDisp
CF
E
WORKSTN INDDS (ERRORINDS)
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
D @NameOk
C
0
D @NameNotFound
C
1
D @NameNotValid
C
2
D @NumErrors
C
2
*
* Indicator data structure for ERRMSG:
*
D ERRORINDS
DS
OCCURS(@NumErrors)
* Indicators for ERRMSG:
D
NotFound
1
1N
D
NotValid
2
2N
*
* Indicators for QUERY:
D
Exit
3
3N
D
Refresh
5
5N
D
Return
12
12N
*
* Prototype for GetName procedure (code not shown)
D GetName
PR
10I 0
D
Name
50A
CONST
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
C
DOU
Exit or Return
C
EXFMT
QUERY
* Check the response indicators
C
SELECT
C
WHEN
Exit or Return
C
RETURN
C
WHEN
Refresh
C
RESET
QUERY
C
ITER
C
ENDSL
*
* Check the name
C
EVAL
RC = GetName(Name)
*
* If it is not valid, display an error message
C
IF
RC <> @NameOk
C
RC
OCCURS
ErrorInds
C
EXFMT
ERRMSG
C
ENDIF
C
ENDDO
...
C
*INZSR
BEGSR
*
* Initialize the occurrences of the ErrorInds data structure
C
@NameNotFound OCCUR
ErrorInds
C
EVAL
NotFound = '1'
C
@NameNotValid OCCUR
ErrorInds
C
EVAL
NotValid = '1'
C
ENDSR
Figure 62. Using a multiple-occurrence indicator data structure
Chapter 8. Defining Data and Prototypes
137
Prototypes and Parameters
Prototypes and Parameters
The recommended way to call programs and procedures is to use prototyped calls,
since prototyped calls allow the compiler to check the call interface at compile time.
If you are coding a subprocedure, you will need to code a procedure-interface definition to allow the compiler to match the call interface to the subprocedure.
This section describes how to define each of these concepts: prototypes, prototyped parameters, and procedure-interface definitions.
Prototypes
A prototype is a definition of the call interface. It includes the following information:
¹ Whether the call is bound (procedure) or dynamic (program)
¹ How to find the program or procedure (the external name)
¹ The number and nature of the parameters
¹ Which parameters must be passed, and which are optionally passed
¹ Whether operational descriptors should be passed
¹ The data type of the return value, if any (for a procedure)
A prototype must be included in the definition specifications of the program or procedure that makes the call. The prototype is used by the compiler to call the
program or procedure correctly, and to ensure that the caller passes the correct
parameters.
The following rules apply to prototype definitions.
¹ A prototype name must be specified in positions 7-21. If the keyword EXTPGM
or EXTPROC is specified on the prototype definition, then any calls to the
program or procedure use the external name specified for that keyword. If
neither keyword is specified, then the external name is the prototype name, that
is, the name specified in positions 7-21 (in uppercase).
¹ Specify PR in the Definition-Type entry (positions 24-25). Any parameter definitions must immediately follow the PR specification. The prototype definition
ends with the first definition specification with non-blanks in positions 24-25 or
by a non-definition specification.
¹ Specify any of the following keywords as they pertain to the call interface:
EXTPROC(name)
The call will be a bound procedure call that uses the external name
specified by the keyword.
EXTPGM(name)
The call will be an external program call that uses the external name
specified by the keyword.
OPDESC Operational descriptors are to be passed with the parameters that
are described in the prototype.
¹ A return value (if any) is specified on the PR definition. Specify the length and
data type of the return value. In addition, you may specify the following
keywords for the return value:
138
ILE RPG for AS/400 Reference
Prototypes and Parameters
DATFMT(fmt)
The return value has the date format specified by the keyword.
DIM(N)
The return value is an array with N elements.
LIKE(name)
The return value is defined like the item specified by the keyword.
PROCPTR
The return value is a procedure pointer.
TIMFMT(fmt)
The return value has the time format specified by the keyword.
|
|
|
VARYING
A character, graphic, or UCS-2 return value has a variable-length
format.
For information on these keywords, see “Definition-Specification Keywords” on
page 279. Figure 63 shows a prototype for a subprocedure CVTCHR that takes a
numeric input parameter and returns a character string. Note that there is no name
associated with the return value. For this reason, you cannot display its contents
when debugging the program.
* The returned value is the character representation of
* the input parameter NUM, left-justified and padded on
* the right with blanks.
D CVTCHR
PR
31A
D
NUM
30P 0
VALUE
* The following expression shows a call to CVTCHR. If
* variable rrn has the value 431, then after this EVAL,
* variable msg would have the value
*
'Record 431 was not found.'
C
EVAL
msg = 'Record '
C
+ %TRIMR(CVTCHR(RRN))
C
+ ' was not found '
Figure 63. Prototype for CVTCHR
Prototyped Parameters
If the prototyped call interface involves the passing of parameters then you must
define the parameter immediately following the PR specification. The following
keywords, which apply to defining the type, are allowed on the parameter definition
specifications:
ASCEND The array is in ascending sequence.
DATFMT(fmt)
The date parameter has the format fmt.
DIM(N)
The parameter is an array with N elements.
LIKE(name)
The parameter is defined like the item specified by the keyword.
PROCPTR
The parameter is a procedure pointer.
Chapter 8. Defining Data and Prototypes
139
Prototypes and Parameters
TIMFMT(fmt)
The time parameter has the format fmt.
|
|
VARYING
A character, graphic, or UCS-2 parameter has a variable-length format.
For information on these keywords, see “Definition-Specification Keywords” on
page 279.
The following keywords, which specify how the parameter should be passed, are
also allowed on the parameter definition specifications:
|
CONST
The parameter is passed by read-only reference. A parameter defined
with CONST must not be modified by the called program or procedure.
This parameter-passing method allows you to pass literals and
expressions.
NOOPT
The parameter will not be optimized in the called program or procedure.
OPTIONS(opt1 { : opt2 { : opt3 { : opt4 { : opt5 } } } })
|
|
Where opt1 ... opt5 can be *NOPASS, *OMIT, *VARSIZE, *STRING, or
*RIGHTADJ. For example, OPTIONS(*VARSIZE : *NOPASS).
Specifies the following parameter passing options:
*NOPASS
The parameter does not have to be passed. If a parameter
has OPTIONS(*NOPASS) specified, then all parameters following it must also have OPTIONS(*NOPASS) specified.
*OMIT
The special value *OMIT may be passed for this reference
parameter.
*VARSIZE
The parameter may contain less data than is indicated on the
definition. This keyword is valid only for character parameters, graphic parameters, UCS-2 parameters, or arrays
passed by reference. The called program or procedure must
have some way of determining the length of the passed
parameter.
|
Note: When this keyword is omitted for fixed-length fields,
the parameter may only contain more or the same
amount of data as indicated on the definition; for
variable-length fields, the parameter must have the
same declared maximum length as indicated on the
definition.
*STRING Pass a character value as a null-terminated string. This
keyword is valid only for basing pointer parameters passed
by value or by read-only reference.
|
|
|
|
*RIGHTADJ
For a CONST or VALUE parameter, *RIGHTADJ indicates
that the graphic, UCS-2, or character parameter value is to
be right adjusted.
140
ILE RPG for AS/400 Reference
Prototypes and Parameters
|
TIP
|
|
|
|
|
|
For the parameter passing options *NOPASS, *OMIT, and
*VARSIZE, it is up to the programmer of the procedure to ensure
that these options are handled. For example, if OPTIONS(*NOPASS)
is coded and you choose to pass the parameter, the procedure must
check that the parameter was passed before it accesses it. The
compiler will not do any checking for this.
VALUE
The parameter is passed by value.
For information on the keywords listed above, see “Definition-Specification
Keywords” on page 279. For more information on using prototyped parameters,
see the chapter on calling programs and procedures in the ILE RPG for AS/400
Programmer's Guide.
Procedure Interface
|
If a prototyped program or procedure has call parameters or a return value, then a
procedure interface definition must be defined, either in the main source section (for
a main procedure) or in the subprocedure section. A procedure interface definition repeats the prototype information within the definition of a procedure. It is
used to declare the entry parameters for the procedure and to ensure that the
internal definition of the procedure is consistent with the external definition (the prototype).
The following rules apply to procedure interface definitions.
¹ The name of the procedure interface, specified in positions 7-21, is optional. If
specified, it must match the name specified in positions 7-21 on the corresponding prototype definition.
¹ Specify PI in the Definition-Type entry (positions 24-25). The procedureinterface definition can be specified anywhere in the definition specifications. In
the main procedure, the procedure interface must be preceded by the prototype
that it refers to. A procedure interface is required in a subprocedure if the procedure returns a value, or if it has any parameters; otherwise, it is optional.
¹ Any parameter definitions, indicated by blanks in positions 24-25, must immediately follow the PI specification.
¹ Parameter names must be specified, although they do not have to match the
names specified on the prototype.
¹ All attributes of the parameters, including data type, length, and dimension,
must match exactly those on the corresponding prototype definition.
¹ The keywords specified on the PI specification and the parameter specifications
must match those specified on the prototype.
Chapter 8. Defining Data and Prototypes
141
Prototypes and Parameters
TIP
If a module contains calls to a prototyped program or procedure, then there
must be a prototype definition for each program and procedure that you want to
call. One way of minimizing the required coding is to store shared prototypes in
/COPY files.
If you provide prototyped programs or procedures to other users, be sure to
provide them with the prototypes (in /COPY files) as well.
142
ILE RPG for AS/400 Reference
Arrays
Chapter 9. Using Arrays and Tables
Arrays and tables are both collections of data fields (elements) of the same:
¹ Field length
¹ Data type
– Character
– Numeric
– Date
– Time
– Timestamp
– Graphic
– Basing Pointer
– Procedure Pointer
|
– UCS-2
¹ Format
¹ Number of decimal positions (if numeric)
Arrays and tables differ in that:
¹ You can refer to a specific array element by its position
¹ You cannot refer to specific table elements by their position
¹ An array name by itself refers to all elements in the array
¹ A table name always refers to the element found in the last “LOOKUP (Look
Up a Table or Array Element)” on page 559 operation
Note: You can define only run-time arrays in a subprocedure. Tables, prerun-time
arrays, and compile-time arrays are not supported.
The next section describes how to code an array, how to specify the initial values
of the array elements, how to change the values of an array, and the special considerations for using an array. The section after next describes the same information for tables.
Arrays
There are three types of arrays:
¹ The run-time array is loaded by your program while it is running.
¹ The compile-time array is loaded when your program is created. The initial
data becomes a permanent part of your program.
¹ The prerun-time array is loaded from an array file when your program begins
running, before any input, calculation, or output operations are processed.
The essentials of defining and loading an array are described for a run-time array.
For defining and loading compile-time and prerun-time arrays you use these essentials and some additional specifications.
 Copyright IBM Corp. 1994, 1999
143
Arrays
Array Name and Index
You refer to an entire array using the array name alone. You refer to the individual
elements of an array using (1) the array name, followed by (2) a left parenthesis,
followed by (3) an index, followed by (4) a right parenthesis -- for example:
AR(IND). The index indicates the position of the element within the array (starting
from 1) and is either a number or a field containing a number.
The following rules apply when you specify an array name and index:
¹ The array name must be a unique symbolic name.
¹ The index must be a numeric field or constant greater than zero and with zero
decimal positions
¹ If the array is specified within an expression in the extended factor 2 field, the
index may be an expression returning a numeric value with zero decimal positions
¹
At run time, if your program refers to an array using an index with a value that
is zero, negative, or greater than the number of elements in the array, then the
error/exception routine takes control of your program.
The Essential Array Specifications
You define an array on a definition specification. Here are the essential specifications for all arrays:
¹ Specify the array name in positions 7 through 21
¹ Specify the number of entries in the array using the DIM keyword
¹ Specify length, data format, and decimal positions as you would any scalar
fields. You may specify explicit From- and To-position entries (if defining a subfield), or an explicit Length-entry; or you may define the array attributes using
the LIKE keyword; or the attributes may be specified elsewhere in the program.
¹ If you need to specify a sort sequence, use the ASCEND or DESCEND
keywords.
Figure 64 shows an example of the essential array specifications.
Coding a Run-Time Array
If you make no further specifications beyond the essential array specifications, you
have defined a run-time array. Note that the keywords ALT, CTDATA, EXTFMT,
FROMFILE, PERRCD, and TOFILE cannot be used for a run-time array.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
DARC
S
3A
DIM(12)
Figure 64. The Essential Array Specifications to Define a Run-Time Array
144
ILE RPG for AS/400 Reference
Arrays
Loading a Run-Time Array
You can assign initial values for a run-time array using the INZ keyword on the
definition specification. You can also assign initial values for a run-time array
through input or calculation specifications. This second method may also be used
to put data into other types of arrays.
For example, you may use the calculation specifications for the MOVE operation to
put 0 in each element of an array (or in selected elements).
Using the input specifications, you may fill an array with the data from a file. The
following sections provide more details on retrieving this data from the records of a
file.
Note: Date and time runtime data must be in the same format and use the same
separators as the date or time array being loaded.
Loading a Run-Time Array in One Source Record
If the array information is contained in one record, the information can occupy consecutive positions in the record or it can be scattered throughout the record.
If the array elements are consecutive on the input record, the array can be loaded
with a single input specification. Figure 65 shows the specifications for loading an
array, INPARR, of six elements (12 characters each) from a single record from the
file ARRFILE.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
DINPARR
S
12A
DIM(6)
IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................
I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr....
IARRFILE
AA 01
I
1
72 INPARR
Figure 65. Using a Run-Time Array with Consecutive Elements
If the array elements are scattered throughout the record, they can be defined and
loaded one at a time, with one element described on a specification line. Figure 66
shows the specifications for loading an array, ARRX, of six elements with 12 characters each, from a single record from file ARRFILE; a blank separates each of the
elements from the others.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
DARRX
S
12A
DIM(6)
IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC................................
I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr....
IARRFILE
AA 01
I
1
12 ARRX(1)
I
14
25 ARRX(2)
I
27
38 ARRX(3)
I
40
51 ARRX(4)
I
53
64 ARRX(5)
I
66
77 ARRX(6)
Figure 66. Defining a Run-Time Array with Scattered Elements
Chapter 9. Using Arrays and Tables
145
Arrays
Loading a Run-Time Array Using Multiple Source Records
If the array information is in more than one record, you may use various methods to
load the array. The method to use depends on the size of the array and whether or
not the array elements are consecutive in the input records. The ILE RPG program
processes one record at a time. Therefore the entire array is not processed until all
the records containing the array information are read and the information is moved
into the array fields. It may be necessary to suppress calculation and output operations until the entire array is read into the program.
Sequencing Run-Time Arrays
Run-time arrays are not sequence checked. If you process a SORTA (sort an
array) operation, the array is sorted into the sequence specified on the definition
specification (the ASCEND or DESCEND keywords) defining the array. If the
sequence is not specified, the array is sorted into ascending sequence. When the
high (positions 71 and 72 of the calculation specifications) or low (positions 73 and
74 of the calculation specifications) indicators are used in the LOOKUP operation,
the array sequence must be specified.
Coding a Compile-Time Array
A compile-time array is specified using the essential array specifications plus the
keyword CTDATA. In addition, on a definition specification you can specify:
¹ The number of array entries in an input record using the PERRCD keyword. If
the keyword is not specified, the number of entries defaults to 1.
¹ The external data format using the EXTFMT keyword. The only allowed values
are L (left-sign), R (right-sign), or S (zoned-decimal). The EXTFMT keyword is
not allowed for float compile-time arrays.
¹ A file to which the array is to be written when the program ends with LR on.
You specify this using the TOFILE keyword.
See Figure 67 on page 147 for an example of a compile-time array.
Loading a Compile-Time Array
For a compile-time array, enter array source data into records in the program
source member. If you use the **ALTSEQ, **CTDATA, and **FTRANS keywords,
the array data may be entered in anywhere following the source records. If you do
not use those keywords, the array data must follow the source records, and any
alternate collating sequence or file translation records in the order in which the
compile-time arrays and tables were defined on the definition specifications. This
data is loaded into the array when the program is compiled. Until the program is
recompiled with new data, the array will always initially have the same values each
time you call the program unless the previous call ended with LR off.
Compile-time arrays can be described separately or in alternating format (with the
ALT keyword). Alternating format means that the elements of one array are intermixed on the input record with elements of another array.
146
ILE RPG for AS/400 Reference
Arrays
Rules for Array Source Records
The rules for array source records are:
¹ The first array entry for each record must begin in position 1.
¹ All elements must be the same length and follow each other with no intervening
spaces
¹ An entire record need not be filled with entries. If it is not, blanks or comments
can be included after the entries (see Figure 67).
¹ If the number of elements in the array as specified on the definition specification is greater than the number of entries provided, the remaining elements are
filled with the default values for the data type specified.
|
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++
DARC
S
3A
DIM(12) PERRCD(5) CTDATA
**CTDATA ARC
48K16343J64044HComments can be placed here
12648A47349K346Comments can be placed here
50B125
Comments can be placed here
48K
163
43J
640
44H
126
48A
473
49K
346
50B
125
This is the compile-time array, ARC.
Figure 67. Array Source Record with Comments
¹ Each record, except the last, must contain the number of entries specified with
the PERRCD keyword on the definition specifications. In the last record,
unused entries must be blank and comments can be included after the unused
entries.
¹ Each entry must be contained entirely on one record. An entry cannot be split
between two records; therefore, the length of a single entry is limited to the
maximum length of 100 characters (size of source record). If arrays are used
and are described in alternating format, corresponding elements must be on the
same record; together they cannot exceed 100 characters.
¹ For date and time compile-time arrays the data must be in the same format and
use the same separators as the date or time array being loaded.
¹ Array data may be specified in one of two ways:
1. **CTDATA arrayname: The data for the array may be specified anywhere in
the compile-time data section.
2. **b: (b=blank) The data for the arrays must be specified in the same order
in which they are specified in the Definition specifications.
Only one of these techniques may be used in one program.
¹ Arrays can be in ascending(ASCEND keyword), descending (DESCEND
keyword), or no sequence (no keyword specified).
¹ For ascending or descending character arrays when ALTSEQ(*EXT) is specified on the control specification, the alternate collating sequence is used for the
sequence checking. If the actual collating sequence is not known at compile
time (for example, if SRTSEQ(*JOBRUN) is specified on a control specification
or as a command parameter) the alternate collating sequence table will be
Chapter 9. Using Arrays and Tables
147
Arrays
retrieved at runtime and the checking will occur during initialization at *INIT.
Otherwise, the checking will be done at compile time.
¹ Graphic and UCS-2 arrays will be sorted by hexadecimal values, regardless of
the alternate collating sequence.
|
|
¹ If L or R is specified on the EXTFMT keyword on the definition specification,
each element must include the sign (+ or -). An array with an element size of 2
with L specified would require 3 positions in the source data as shown in the
following example.
*....+....1....+....2....+....3....+....4....+....5....+....6....+....*
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++
D UPDATES
2 0 DIM(5) PERRCD(5) EXTFMT(L) CTDATA
**CTDATA UDPATES
+37-38+52-63-49+51
¹ Float compile-time data are specified in the source records as float or numeric
literals. Arrays defined as 4-byte float require 14 positions for each element;
arrays defined as 8-byte float require 23 positions for each element.
¹ Graphic data must be enclosed in shift-out and shift-in characters. If several
elements of graphic data are included in a single record (without intervening
nongraphic data) only one set of shift-out and shift-in characters is required for
the record. If a graphic array is defined in alternating format with a nongraphic
array, the shift-in and shift-out characters must surround the graphic data. If
two graphic arrays are defined in alternating format, only one set of shift-in and
shift-out characters is required for each record.
Coding a Prerun-Time Array
In addition to the essential array specifications, you can also code the following
specifications or keywords for prerun-time arrays.
On the definition specifications, you can specify
¹ The name of the file with the array input data, using the FROMFILE keyword.
¹ The name of a file to which the array is written at the end of the program, using
the TOFILE keyword.
¹ The number of elements per input record, using the PERRCD keyword.
¹ The external format of numeric array data using the EXTFMT keyword.
¹ An alternating format using the ALT keyword.
Note: The integer or unsigned format cannot be specified for arrays defined with
more than ten digits.
On the file-description specifications, you can specify a T in position 18 for the file
with the array input data.
Example of Coding Arrays
Figure 68 on page 149 shows the definition specifications required for two preruntime arrays, a compile-time array, and a run-time array.
148
ILE RPG for AS/400 Reference
Arrays
*....+....1....+....2....+....3....+....4....+....5....+....6....+....*
HKeywords+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
H DATFMT(*USA) TIMFMT(*HMS)
D*ame+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++
* Run-time array. ARI has 10 elements of type date. They are
* initialized to September 15, 1994. This is in month, day,
* year format using a slash as a separator as defined on the
* control specification.
DARI
S
D
DIM(10) INZ(D'09/15/1994')
*
* Compile-time arrays in alternating format. Both arrays have
* eight elements (three elements per record). ARC is a character
* array of length 15, and ARD is a time array with a predefined
* length of 8.
DARC
S
15
DIM(8) PERRCD(3)
D
CTDATA
DARD
S
T
DIM(8) ALT(ARC)
*
* Prerun-time array. ARE, which is to be read from file DISKIN,
* has 250 character elements (12 elements per record). Each
* element is five positions long. The size of each record
* is 60 (5*12). The elements are arranged in ascending sequence.
DARE
S
5A
DIM(250) PERRCD(12) ASCEND
D
FROMFILE(DISKIN)
*
* Prerun-time array specified as a combined file. ARH is written
* back to the same file from which it is read when the program
* ends normally with LR on. ARH has 250 character elements
* (12 elements per record). Each elements is five positions long.
* The elements are arranged in ascending sequence.
DARH
S
5A
DIM(250) PERRCD(12) ASCEND
D
FROMFILE(DISKOUT)
D
TOFILE(DISKOUT)
**CTDATA ARC
Toronto
12:15:00Winnipeg
13:23:00Calgary
15:44:00
Sydney
17:24:30Edmonton
21:33:00Saskatoon
08:40:00
Regina
12:33:00Vancouver
13:20:00
Figure 68. Definition Specifications for Different Types of Arrays
Loading a Prerun-Time Array
For a prerun-time array, enter array input data into a file. The file must be a
sequential program described file. During initialization, but before any input, calculation, or output operations are processed the array is loaded with initial values
from the file. By modifying this file, you can alter the array's initial values on the
next call to the program, without recompiling the program. The file is read in arrival
sequence. The rules for prerun-time array data are the same as for compile-time
array data, except there are no restrictions on the length of each record. See
“Rules for Array Source Records” on page 147.
Sequence Checking for Character Arrays
Sequence checking for character arrays that have not been defined with
ALTSEQ(*NONE) has two dependencies:
1. Whether the ALTSEQ control specification keyword has been specified, and if
so, how.
2. Whether the array is compile time or prerun time.
Chapter 9. Using Arrays and Tables
149
Initializing Arrays
The following table indicates when sequence checking occurs.
Control Specification Entry
ALTSEQ Used for
SORTA, LOOKUP
and Sequence
Checking
When Sequence
Checked for
Compile Time
Array
When Sequence
Checked for
Prerun Time
Array
ALTSEQ(*NONE)
No
Compile time
Run time
ALTSEQ(*SRC)
No
Compile time
Run time
ALTSEQ(*EXT)
(known at compile
time)
Yes
Compile time
Run time
ALTSEQ(*EXT)
(known only at run
time)
Yes
Run time
Run time
Note: For compatibility with RPG III, SORTA and LOOKUP do not use the alternate collating sequence with ALTSEQ(*SRC). If you want these operations
to be performed using the alternate collating sequence, you can define a
table on the system (object type *TBL), containing your alternate sequence.
Then you can change ALTSEQ(*SRC) to ALTSEQ(*EXT) on your control
specification and specify the name of your table on the SRTSEQ keyword
or parameter of the create command.
Initializing Arrays
Run-Time Arrays
To initialize each element in a run-time array to the same value, specify the INZ
keyword on the definition specification. If the array is defined as a data structure
subfield, the normal rules for data structure initialization overlap apply (the initialization is done in the order that the fields are declared within the data structure).
Compile-Time and Prerun-Time Arrays
The INZ keyword cannot be specified for a compile-time or prerun-time array,
because their initial values are assigned to them through other means (compiletime data or data from an input file). If a compile-time or prerun-time array appears
in a globally initialized data structure, it is not included in the global initialization.
Note: Compile-time arrays are initialized in the order in which the data is declared
after the program, and prerun-time arrays are initialized in the order of declaration of their initialization files, regardless of the order in which these
arrays are declared in the data structure. Pre-run time arrays are initialized
after compile-time arrays.
If a subfield initialization overlaps a compile-time or prerun-time array, the initialization of the array takes precedence; that is, the array is initialized after the subfield,
regardless of the order in which fields are declared within the data structure.
150
ILE RPG for AS/400 Reference
Defining Related Arrays
Defining Related Arrays
You can load two compile-time arrays or two prerun-time arrays in alternating
format by using the ALT keyword on the definition of the alternating array. You
specify the name of the primary array as the parameter for the ALT keyword. The
records for storing the data for such arrays have the first element of the first array
followed by the first element of the second array, the second element of the first
array followed by the second element of the second array, the third element of the
first array followed by the third element of the second array, and so on. Corresponding elements must appear on the same record. The PERRCD keyword on the
main array definition specifies the number of corresponding pairs per record, each
pair of elements counting as a single entry. You can specify EXTFMT on both the
main and alternating array.
Figure 69 shows two arrays, ARRA and ARRB, in alternating format.
A R R A
(Part Number)
A R R B
(Unit Cost)
345126
373
38A437
498
39K143
1297
40B125
93
41C023
3998
42D893
87
43K823
349
44H111
697
45P673
898
46C732
47587
Arrays ARRA and ARRB can be described
as two separate array files or as one
array file in alternating format.
Figure 69. Arrays in Alternating and Nonalternating Format
The records for ARRA and ARRB look like the records below when described as
two separate array files.
This record contains ARRA entries in positions 1 through 60.
ARRA
entry
ARRA
entry
ARRA
entry
ARRA
entry
ARRA
entry
ARRA
entry
ARRA
entry
ARRA
entry
ARRA
entry
ARRA
entry
1 . . . . . 7 . . . . . 13 . . . . 19 . . . . 25 . . . . 31 . . . . 37 . . . . 43 . . . . 49 . . . . 55 . . . .
Figure 70. Arrays Records for Two Separate Array Files
This record contains ARRB entries in positions 1 through 50.
Chapter 9. Using Arrays and Tables
151
Searching Arrays
ARRB
entry
1.....
ARRB
entry
ARRB
entry
ARRB
entry
ARRB
entry
ARRB
entry
ARRB
entry
ARRB
entry
ARRB
entry
ARRB
entry
6 . . . . . 11 . . . . 16 . . . . 21 . . . . 26 . . . . 31 . . . . 36 . . . . 41 . . . . 46 . . . .
Figure 71. Arrays Records for One Array File
The records for ARRA and ARRB look like the records below when described as
one array file in alternating format. The first record contains ARRA and ARRB
entries in alternating format in positions 1 through 55. The second record contains
ARRA and ARRB entries in alternating format in positions 1 through 55.
ARRA
entry
1.....
ARRB
entry
ARRA
entry
ARRB
entry
ARRA
entry
ARRB
entry
ARRA
entry
ARRB
entry
ARRA
entry
ARRB
entry
1 . . . . . 7 . . . . . 6 . . . . . 13 . . . . 11 . . . . 19 . . . . 16 . . . . 25 . . . . 21 . . . .
Figure 72. Arrays Records for One Array File in Alternating Format
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++
DARRA
S
6A
DIM(6) PERRCD(1) CTDATA
DARRB
S
5 0 DIM(6) ALT(ARRA)
DARRGRAPHIC
S
3G
DIM(2) PERRCD(2) CTDATA
DARRC
S
3A
DIM(2) ALT(ARRGRAPHIC)
DARRGRAPH1
S
3G
DIM(2) PERRCD(2) CTDATA
DARRGRAPH2
S
3G
DIM(2) ALT(ARRGRAPH1)
**CTDATA ARRA
345126 373
38A437 498
39K143 1297
40B125
93
41C023 3998
42D893
87
**CTDATA ARRGRAPHIC
ok1k2k3iabcok4k5k6iabc
**CTDATA ARRGRAPH1
ok1k2k3k4k5k6k1k2k3k4k5k6i
Searching Arrays
The LOOKUP operation can be used to search arrays. See “LOOKUP (Look Up a
Table or Array Element)” on page 559 for a description of the LOOKUP operation.
Searching an Array Without an Index
When searching an array without an index, use the status (on or off) of the
resulting indicators to determine whether a particular element is present in the
array. Searching an array without an index can be used for validity checking of
input data to determine if a field is in a list of array elements. Generally, an equal
LOOKUP is requested.
In factor 1 in the calculation specifications, specify the search argument (data for
which you want to find a match in the array named) and place the array name
factor 2.
152
ILE RPG for AS/400 Reference
Searching Arrays
In factor 2 specify the name of the array to be searched. At least one resulting
indicator must be specified. Entries must not be made in both high and low for the
same LOOKUP operation. The resulting indicators must not be specified in high or
low if the array is not in sequence (ASCEND or DESCEND keywords). Control level
and conditioning indicators (specified in positions 7 through 11) can also be used.
The result field cannot be used.
The search starts at the beginning of the array and ends at the end of the array or
when the conditions of the lookup are satisfied. Whenever an array element is
found that satisfies the type of search being made (equal, high, low), the resulting
indicator is set on.
Figure 73 shows an example of a LOOKUP on an array without an index.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++
FARRFILE
IT
F
5
DISK
F*
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
DDPTNOS
S
5S 0 DIM(50) FROMFILE(ARRFILE)
D*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
C* The LOOKUP operation is processed and, if an element of DPTNOS equal
C* to the search argument (DPTNUM) is found, indicator 20 is set on.
C
DPTNUM
LOOKUP
DPTNOS
20
Figure 73. LOOKUP Operation for an Array without an Index
ARRFILE, which contains department numbers, is defined in the file description
specifications as an input file (I in position 17) with an array file designation (T in
position 18). The file is program described (F in position 22), and each record is 5
positions in length (5 in position 27).
In the definition specifications, ARRFILE is defined as containing the array
DPTNOS. The array contains 50 entries (DIM(50)). Each entry is 5 positions in
length (positions 33-39) with zero decimal positions (positions 41-42). One department number can be contained in each record (PERRCD defaults to 1).
Searching an Array with an Index
To find out which element satisfies a LOOKUP search, start the search at a particular element in the array. To do this type of search, make the entries in the calculation specifications as you would for an array without an index. However, in factor
2, enter the name of the array to be searched, followed by a parenthesized numeric
field (with zero decimal positions) containing the number of the element at which
the search is to start. This numeric constant or field is called the index because it
points to a certain element in the array. The index is updated with the element
number which satisfied the search or is set to 0 if the search failed.
You can use a numeric constant as the index to test for the existence of an
element that satisfies the search starting at an element other than 1.
All other rules that apply to an array without an index apply to an array with an
index.
Figure 74 on page 154 shows a LOOKUP on an array with an index.
Chapter 9. Using Arrays and Tables
153
Using Arrays
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++
FARRFILE
IT
F
25
DISK
F*
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
DDPTNOS
S
5S 0 DIM(50) FROMFILE(ARRFILE)
DDPTDSC
S
20A
DIM(50) ALT(DPTNOS)
D*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
C* The Z-ADD operation begins the LOOKUP at the first element in DPTNOS.
C
Z-ADD
1
X
3 0
C* At the end of a successful LOOKUP, when an element has been found
C* that contains an entry equal to the search argument DPTNUM,
C* indicator 20 is set on and the MOVE operation places the department
C* description, corresponding to the department number, into DPTNAM.
C
DPTNUM
LOOKUP
DPTNOS(X)
20
C* If an element is not found that is equal to the search argument,
C* element X of DPTDSC is moved to DPTNAM.
C
IF
NOT *IN20
C
MOVE
DPTDSC(X)
DPTNAM
20
C
ENDIF
Figure 74. LOOKUP Operation on an Array with an Index
This example shows the same array of department numbers, DPTNOS, as
Figure 73 on page 153. However, an alternating array of department descriptions,
DPTDSC, is also defined. Each element in DPTDSC is 20 positions in length. If
there is insufficient data in the file to initialize the entire array, the remaining elements in DPTNOS are filled with zeros and the remaining elements in DPTDSC are
filled with blanks.
Using Arrays
Arrays can be used in input, output, or calculation specifications.
Specifying an Array in Calculations
An entire array or individual elements in an array can be specified in calculation
specifications. You can process individual elements like fields.
A noncontiguous array defined with the OVERLAY keyword cannot be used with
the MOVEA operation or in the result field of a PARM operation.
To specify an entire array, use only the array name, which can be used as factor 1,
factor 2, or the result field. The following operations can be used with an array
name: ADD, Z-ADD, SUB, Z-SUB, MULT, DIV, SQRT, ADDDUR, SUBDUR, EVAL,
EXTRCT, MOVE, MOVEL, MOVEA, MLLZO, MLHZO, MHLZO, MHHZO, DEBUG,
XFOOT, LOOKUP, SORTA, PARM, DEFINE, CLEAR, RESET, CHECK, CHECKR,
and SCAN.
Several other operations can be used with an array element only but not with the
array name alone. These operations include but are not limited to: BITON, BITOFF,
COMP, CABxx, TESTZ, TESTN, TESTB, MVR, DO, DOUxx, DOWxx, DOU, DOW,
IFxx, WHENxx, WHEN, IF, SUBST, and CAT.
When specified with an array name without an index or with an asterisk as the
index (for example, ARRAY or ARRAY(*)) certain operations are repeated for each
154
ILE RPG for AS/400 Reference
Sorting Arrays
element in the array. These are ADD, Z-ADD, EVAL, SUB, Z-SUB, ADDDUR,
SUBDUR, EXTRCT, MULT, DIV, SQRT, MOVE, MOVEL, MLLZO, MLHZO, MHLZO
and MHHZO. The following rules apply to these operations when an array name
without an index is specified:
¹ When factors 1 and 2 and the result field are arrays with the same number of
elements, the operation uses the first element from every array, then the
second element from every array until all elements in the arrays are processed.
If the arrays do not have the same number of entries, the operation ends when
the last element of the array with the fewest elements has been processed.
When factor 1 is not specified for the ADD, SUB, MULT, and DIV operations,
factor 1 is assumed to be the same as the result field.
¹ When one of the factors is a field, a literal, or a figurative constant and the
other factor and the result field are arrays, the operation is done once for every
element in the shorter array. The same field, literal, or figurative constant is
used in all of the operations.
¹ The result field must always be an array.
¹ If an operation code uses factor 2 only (for example, Z-ADD, Z-SUB, SQRT,
ADD, SUB, MULT, or DIV may not have factor 1 specified) and the result field
is an array, the operation is done once for every element in the array. The
same field or constant is used in all of the operations if factor 2 is not an array.
¹ Resulting indicators (positions 71 through 76) cannot be used because of the
number of operations being processed.
¹ In an EVAL expression, if any arrays on the right-hand side are specified
without an index, the left-hand side must also contain an array without an
index.
Note: When used in an EVAL operation %ADDR(arr) and %ADDR(arr(*)) do not
have the same meaning. See “%ADDR (Get Address of Variable)” on
page 363 for more detail.
Sorting Arrays
You can sort arrays using the “SORTA (Sort an Array)” on page 657 operation
code. The array is sorted into sequence (ascending or descending), depending on
the sequence specified for the array on the definition specification.
Sorting using part of the array as a key
You can use the OVERLAY keyword to overlay one array over another. For
example, you can have a base array which contains names and salaries and two
overlay arrays (one for the names and one for the salaries). You could then sort the
base array by either name or salary by sorting on the appropriate overlay array.
Chapter 9. Using Arrays and Tables
155
Array Output
*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D
DS
D Emp_Info
50
DIM(500) ASCEND
D
Emp_Name
45
OVERLAY(Emp_Info:1)
D
Emp_Salary
9P 2 OVERLAY(Emp_Info:46)
D
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
C
C* The following SORTA sorts Emp_Info by employee name.
C* The sequence of Emp_Name is used to determine the order of the
C* elements of Emp_Info.
C
SORTA
Emp_Name
C* The following SORTA sorts Emp_Info by employee salary
C* The sequence of Emp_Salary is used to determine the order of the
C* elements of Emp_Info.
C
SORTA
Emp_Salary
Figure 75. SORTA Operation with OVERLAY
Array Output
Entire arrays can be written out under ILE RPG control only at end of program
when the LR indicator is on. To indicate that an entire array is to be written out,
specify the name of the output file with the TOFILE keyword on the definition specifications. This file must be described as a sequentially organized output or combined file in the file description specifications. If the file is a combined file and is
externally described as a physical file, the information in the array at the end of the
program replaces the information read into the array at the start of the program.
Logical files may give unpredictable results.
If an entire array is to be written to an output record (using output specifications),
describe the array along with any other fields for the record:
¹ Positions 30 through 43 of the output specifications must contain the array
name used in the definition specifications.
¹ Positions 47 through 51 of the output specifications must contain the record
position where the last element of the array is to end. If an edit code is specified, the end position must include blank positions and any extensions due to
the edit code (see “Editing Entire Arrays” listed next in this chapter).
Output indicators (positions 21 through 29) can be specified. Zero suppress (position 44), blank-after (position 45), and data format (position 52) entries pertain to
every element in the array.
Editing Entire Arrays
When editing is specified for an entire array, all elements of the array are edited. If
different editing is required for various elements, refer to them individually.
When an edit code is specified for an entire array (position 44), two blanks are
automatically inserted between elements in the array: that is, there are blanks to
the left of every element in the array except the first. When an edit word is specified, the blanks are not inserted. The edit word must contain all the blanks to be
inserted.
156
ILE RPG for AS/400 Reference
Tables
Editing of entire arrays is only valid in output specifications, not with the %EDITC or
%EDITW built-in functions.
Tables
The explanation of arrays applies to tables except for the following differences:
Activity
Differences
Defining
A table name must be a unique symbolic name that begins with the
letters TAB.
Loading
Tables can be loaded only at compilation time and prerun-time.
Using and Modifying table elements
Only one element of a table is active at one time. The table name is
used to refer to the active element. An index cannot be specified for a
table.
Searching
The LOOKUP operation is specified differently for tables.
Note: You cannot define a table in a subprocedure.
LOOKUP with One Table
When a single table is searched, factor 1, factor 2, and at least one resulting indicator must be specified. Conditioning indicators (specified in positions 7 through 11)
can also be used.
Whenever a table element is found that satisfies the type of search being made
(equal, high, low), that table element is made the current element for the table. If
the search is not successful, the previous current element remains the current
element.
Before a first successful LOOKUP, the first element is the current element.
Resulting indicators reflect the result of the search. If the indicator is on, reflecting a
successful search, the element satisfying the search is the current element.
LOOKUP with Two Tables
When two tables are used in a search, only one is actually searched. When the
search condition (high, low, equal) is satisfied, the corresponding elements are
made available for use.
Factor 1 must contain the search argument, and factor 2 must contain the name of
the table to be searched. The result field must name the table from which data is
also made available for use. A resulting indicator must also be used. Control level
and conditioning indicators can be specified in positions 7 through 11, if needed.
The two tables used should have the same number of entries. If the table that is
searched contains more elements than the second table, it is possible to satisfy the
search condition. However, there might not be an element in the second table that
corresponds to the element found in the search table. Undesirable results can
occur.
Note: If you specify a table name in an operation other than LOOKUP before a
successful LOOKUP occurs, the table is set to its first element.
Chapter 9. Using Arrays and Tables
157
Tables
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
C* The LOOKUP operation searches TABEMP for an entry that is equal to
C* the contents of the field named EMPNUM. If an equal entry is
C* found in TABEMP, indicator 09 is set on, and the TABEMP entry and
C* its related entry in TABPAY are made the current elements.
C
EMPNUM
LOOKUP
TABEMP
TABPAY
09
C* If indicator 09 is set on, the contents of the field named
C* HRSWKD are multiplied by the value of the current element of
C* TABPAY.
C
IF
*IN09
C
HRSWKD
MULT(H)
TABPAY
AMT
6 2
C
ENDIF
Figure 76. Searching for an Equal Entry
Specifying the Table Element Found in a LOOKUP Operation
Whenever a table name is used in an operation other than LOOKUP, the table
name actually refers to the data retrieved by the last successful search. Therefore,
when the table name is specified in this fashion, elements from a table can be used
in calculation operations.
If the table is used as factor 1 in a LOOKUP operation, the current element is used
as the search argument. In this way an element from a table can itself become a
search argument.
The table can also be used as the result field in operations other than the LOOKUP
operation. In this case the value of the current element is changed by the calculation specification. In this way the contents of the table can be modified by calculation operations (see Figure 77).
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
C
ARGMNT
LOOKUP
TABLEA
20
C* If element is found multiply by 1.5
C* If the contents of the entire table before the MULT operation
C* were 1323.5, -7.8, and 113.4 and the value of ARGMNT is -7.8,
C* then the second element is the current element.
C* After the MULT operation, the entire table now has the
C* following value: 1323.5, -11.7, and 113.4.
C* Note that only the second element has changed since that was
C* the current element, set by the LOOKUP.
C
IF
*IN20
C
TABLEA
MULT
1.5
TABLEA
C
ENDIF
Figure 77. Specifying the Table Element Found in LOOKUP Operations
158
ILE RPG for AS/400 Reference
Internal and External Formats
Chapter 10. Data Types and Data Formats
This chapter describes the data types supported by RPG IV and their special characteristics. The supported data types are:
¹ Character
¹ Numeric
¹ Graphic
|
¹ UCS-2
¹ Date
¹ Time
¹ Timestamp
¹ Basing Pointer
¹ Procedure Pointer
In addition, some of the data types allow different data formats. This chapter
describes the difference between internal and external data formats, describes each
format, and how to specify them.
Internal and External Formats
Numeric, character, date, time, and timestamp fields have an internal format that is
independent of the external format. The internal format is the way the data is
stored in the program. The external format is the way the data is stored in files.
You need to be aware of the internal format when:
¹ Passing parameters by reference
¹ Overlaying subfields in data structures
In addition, you may want to consider the internal format of numeric fields, when
the run-time performance of arithmetic operations is important. For more information, see “Performance Considerations” on page 434.
There is a default internal and external format for numeric and date-time data
types. You can specify an internal format for a specific field on a definition specification. Similarly, you can specify an external format for a program-described field
on the corresponding input or output specification.
For fields in an externally described file, the external data format is specified in the
data description specifications in position 35. You cannot change the external
format of externally described fields, with one exception. If you specify EXTBININT
on a control specification, any binary field with zero decimal positions will be treated
as having an integer external format.
For subfields in externally described data structures, the data formats specified in
the external description are used as the internal formats of the subfields by the
compiler.
 Copyright IBM Corp. 1994, 1999
159
Internal and External Formats
Internal Format
The default internal format for numeric standalone fields is packed-decimal. The
default internal format for numeric data structure subfields is zoned-decimal. To
specify a different internal format, specify the format desired in position 40 on the
definition specification for the field or subfield.
The default format for date, time, and timestamp fields is *ISO. In general, it is
recommended that you use the default ISO internal format, especially if you have a
mixture of external format types.
For date, time, and timestamp fields, you can use the DATFMT and TIMFMT
keywords on the control specification to change the default internal format, if
desired, for all date-time fields in the program. You can use the DATFMT or
TIMFMT keyword on a definition specification to override the default internal format
of an individual date-time field.
External Format
|
If you have numeric, character, or date-time fields in program-described files, you
can specify their external format.
The external format does not affect the way in which a field is processed.
However, you may be able to improve performance of arithmetic operations,
depending on the internal format specified. For more information, see “Performance
Considerations” on page 434.
The following table shows how to specify the external format of program-described
fields. For more information on each format type, see the appropriate section in the
remainder of this chapter.
Table 11. Entries and Locations for Specifying External Formats
Type of Field
Input
Output
Array or Table
Specification
Using
Input
Position 36
Output
Position 52
Definition
EXTFMT keyword
Specifying an External Format for a Numeric Field
|
|
For any of the fields in Table 11, specify one of the following valid external numeric
formats:
160
B
Binary
F
Float
I
Integer
L
Left sign
P
Packed decimal
R
Right sign
S
Zoned decimal
U
Unsigned
ILE RPG for AS/400 Reference
Internal and External Formats
The default external format for float numeric data is called the external display representation. The format for 4-byte float data is:
+n.nnnnnnnE+ee,
where + represents the sign (+ or -)
n represents digits in the mantissa
e represents digits in the exponent
The format for 8-byte float data is:
+n.nnnnnnnnnnnnnnnE+eee
Note that a 4-byte float value occupies 14 positions and an 8-byte float value occupies 23 positions.
For numeric data other than float, the default external format is zoned decimal. The
external format for compile-time arrays and tables must be zoned-decimal, left-sign
or right-sign.
For float compile-time arrays and tables, the compile-time data is specified as either
a numeric literal or a float literal. Each element of a 4-byte float array requires 14
positions in the source record; each element of an 8-byte float array requires 23
positions.
Non-float numeric fields defined on input specifications, calculation specifications, or
output specifications with no corresponding definition on a definition specification
are stored internally in packed-decimal format.
|
|
|
|
Specifying an External Format for a Character, Graphic, or
UCS-2 Field
|
A
Character (valid for character and indicator data)
|
N
Indicator (valid for character and indicator data)
|
G
Graphic (valid for graphic data)
|
C
UCS-2 (valid for UCS-2 data)
|
|
The EXTFMT keyword can be used to specify the data for an array or table in
UCS-2 format.
|
|
|
Specify the *VAR data attribute in positions 31-34 on an input specification and in
positions 53-80 on an output specification for variable-length character, graphic, or
UCS-2 data.
For any of the input and output fields in Table 11 on page 160, specify one of the
following valid external data formats:
Specifying an External Format for a Date-Time Field
If you have date, time, and timestamp fields in program-described files, then you
must specify their external format. You can specify a default external format for all
date, time, and timestamp fields in a program-described file by using the DATFMT
and TIMFMT keywords on a file description specification. You can specify an
external format for a particular field as well. Specify the desired format in positions
31-34 on an input specification. Specify the appropriate keyword and format in positions 53-80 on an output specification.
Chapter 10. Data Types and Data Formats
161
Character, Graphic and UCS-2 Data
For more information on each format type, see the appropriate section in the
remainder of this chapter.
Character Data Type
The character data type represents character values and may have any of the following formats:
|
|
|
|
A
Character
N
Indicator
G
Graphic
C
UCS-2
Character data may contain one or more single-byte or double-byte characters,
depending on the format specified. Character, graphic, and UCS-2 fields can also
have either a fixed or variable-length format. The following table summarizes the
different character data-type formats.
|
|
Character
Data Type
Number of Bytes
CCSID
Character
One or more single-byte characters that are fixed or variable
in length
assumed to be the graphic
CCSID related to the runtime job
CCSID
Indicator
One single-byte character that
is fixed in length
assumed to be the graphic
CCSID related to the runtime job
CCSID
Graphic
One or more double-byte characters that are fixed or variable
in length
65535 or a CCSID with the
EBCDIC double-byte encoding
scheme (x'1200')
UCS-2
One or more double-byte characters that are fixed or variable
in length
13488 (UCS-2 version 2.0)
For information on the CCSIDs of character data, see “Conversion between Character, Graphic and UCS-2 Data” on page 173.
Character Format
The fixed-length character format is one or more bytes long with a set length.
|
|
For information on the variable-length character format, see “Variable-Length Character, Graphic and UCS-2 Formats” on page 165.
You define a character field by specifying A in the Data-Type entry of the appropriate specification. You can also define one using the LIKE keyword on the definition specification where the parameter is a character field.
The default initialization value is blanks.
162
ILE RPG for AS/400 Reference
Character, Graphic and UCS-2 Data
Indicator Format
The indicator format is a special type of character data. Indicators are all one byte
long and can only contain the character values '0' (off) and '1' (on). They are generally used to indicate the result of an operation or to condition (control) the processing of an operation. The default value of indicators is '0'.
You define an indicator field by specifying N in the Data-Type entry of the appropriate specification. You can also define an indicator field using the LIKE keyword
on the definition specification where the parameter is an indicator field. Indicator
fields are also defined implicitly with the COMMIT keyword on the file description
specification.
A special set of predefined RPG IV indicators (*INxx) is also available. For a
description of these indicators, see Chapter 4, “RPG IV Indicators” on page 33.
The rules for defining indicator variables are:
¹ Indicators can be defined as standalone fields, subfields, prototyped parameters, and procedure return values.
¹ If an indicator variable is defined as a prerun-time or compile-time array or
table, the initialization data must consist of only '0's and '1's.
Note: If an indicator contains a value other than '0' or '1' at runtime, the
results are unpredictable.
¹ If the keyword INZ is specified, the value must be one of '0', *OFF, '1', or *ON.
¹ The keyword VARYING cannot be specified for an indicator field.
The rules for using indicator variables are:
¹ The default initialization value for indicator fields is '0'.
¹ Operation code CLEAR sets an indicator variable to '0'.
¹ Blank-after function applied to an indicator variable sets it to '0'.
¹ If an array of indicators is specified as the result of a MOVEA(P) operation, the
padding character is '0'.
¹ Indicators are implicitly defined with ALTSEQ(*NONE). This means that the
alternate collating sequence is not used for comparisons involving indicators.
¹ Indicators may be used as key-fields where the external key is a character of
length 1.
Graphic Format
The graphic format is a character string where each character is represented by 2
bytes.
Fields defined as graphic data do not contain shift-out (SO) or shift-in (SI) characters. The difference between single byte character and double byte graphic data is
shown in the following figure:
Chapter 10. Data Types and Data Formats
163
Character, Graphic and UCS-2 Data
1 byte
1 byte
1 byte
1 byte
Single-byte
data
1 char
1 char
1 char
1 char
1 byte
1 byte
1 byte
1 byte
Graphic
data
1 graphic char
1 graphic char
Figure 78. Comparing Single-byte and graphic data
The length of a graphic field, in bytes, is two times the number of graphic characters in the field.
The fixed-length graphic format is a character string with a set length where each
character is represented by 2 bytes.
|
|
For information on the variable-length graphic format, see “Variable-Length Character, Graphic and UCS-2 Formats” on page 165.
You define a graphic field by specifying G in the Data-Type entry of the appropriate
specification. You can also define one using the LIKE keyword on the definition
specification where the parameter is a graphic field.
The default initialization value for graphic data is X'4040'. The value of *HIVAL is
X'FFFF', and the value of *LOVAL is X'0000'.
|
|
|
|
UCS-2 Format
The Universal Character Set (UCS-2) format is a character string where each character is represented by 2 bytes. This character set can encode the characters for
many written languages.
|
|
Fields defined as UCS-2 data do not contain shift-out (SO) or shift-in (SI) characters.
|
|
The length of a UCS-2 field, in bytes, is two times the number of UCS-2 characters
in the field.
|
|
The fixed-length UCS-2 format is a character string with a set length where each
character is represented by 2 bytes.
|
|
For information on the variable-length UCS-2 format, see “Variable-Length Character, Graphic and UCS-2 Formats” on page 165.
|
|
|
You define a UCS-2 field by specifying C in the Data-Type entry of the appropriate
specification. You can also define one using the LIKE keyword on the definition
specification where the parameter is a UCS-2 field.
164
ILE RPG for AS/400 Reference
Character, Graphic and UCS-2 Data
|
|
The default initialization value for UCS-2 data is X'0020'. The value of *HIVAL is
X'FFFF', *LOVAL is X'0000', and the value of *BLANKS is X'0020'.
|
|
|
For more information on the UCS-2 format, see the International Application Development, National Language Support, and System API Reference: National Language Support APIs manuals.
Variable-Length Character, Graphic and UCS-2 Formats
|
|
|
|
|
Variable-length character fields have a declared maximum length and a current
length that can vary while a program is running. The length is measured in single
bytes for the character format and in double bytes for the graphic and UCS-2
formats. The storage allocated for variable-length character fields is 2 bytes longer
than the declared maximum length. The leftmost 2 bytes are an unsigned integer
field containing the current length in characters, graphic characters or UCS-2 characters . The actual character data starts at the third byte of the variable-length field.
Figure 79 shows how variable-length character fields are stored:
current
length
character-data
UNS(5)
CHAR(N)
N = declared maximum length
2 + N = total number of bytes
Figure 79. Character Fields with Variable-Length Format
|
|
Figure 80 shows how variable-length graphic fields are stored. UCS-2 fields are
stored similarly.
current
length
UNS(5)
graphic-data
GRAPHIC(N)
N = declared maximum length = number of double bytes
2 + 2(N) = total number of bytes
Figure 80. Graphic Fields with Variable-Length Format
Note: Only the data up to and including the current length is significant.
You define a variable-length character data field by specifying A (character), G
(graphic), or C (UCS-2) and the keyword VARYING on a definition specification. It
can also be defined using the LIKE keyword on a definition specification where the
parameter is a variable-length character field.
You can refer to external variable-length fields, on an input or output specification,
with the *VAR data attribute.
A variable-length field is initialized by default to have a current length of zero.
For examples of using variable-length fields, see:
Chapter 10. Data Types and Data Formats
165
Character, Graphic and UCS-2 Data
¹ “Using Variable-Length Fields” on page 168
|
¹ “%LEN (Get or Set Length)” on page 385
¹ “%CHAR (Convert to Character Data)” on page 365
¹ “%REPLACE (Replace Character String)” on page 394.
Rules for Variable-Length Character, Graphic, and UCS-2
Formats
The following rules apply when defining variable-length fields:
¹ The declared length of the field can be from 1 to 65535 single-byte characters
and from 1 to 16383 double-byte graphic or UCS-2 characters.
|
|
¹ The current length may be any value from 0 to the maximum declared length
for the field.
¹ The field may be initialized using keyword INZ. The initial value is the exact
value specified and the initial length of the field is the length of the initial value.
The field is padded with blanks for initialization, but the blanks are not included
in the length.
¹ In all cases except subfields defined using positional notation, the length entry
(positions 33-39 on the definition specifications) contains the maximum length
of the field not including the 2-byte length.
¹ For subfields defined using positional notation, the length includes the 2-byte
length. As a result, a variable-length subfield may be 32769 single bytes long
or 16384 double bytes long for an unnamed data structure.
|
|
¹ The keyword VARYING cannot be specified for a data structure.
¹ For variable-length prerun-time arrays, the initialization data in the file is stored
in variable format, including the 2-byte length prefix.
¹ Since prerun-time array data is read from a file and files have a maximum
record length of 32766, variable-length prerun-time arrays have a maximum
size of 32764 single-byte characters, or 16382 double-byte graphic or UCS-2
characters.
|
|
¹ A variable-length array or table may be defined with compile-time data. The
trailing blanks in the field of data are not significant. The length of the data is
the position of the last non-blank character in the field. This is different from
prerun-time initialization since the length prefix cannot be stored in compile-time
data.
¹ *LIKE DEFINE cannot be used to define a field like a variable-length field.
The following is an example of defining variable-length character fields:
166
ILE RPG for AS/400 Reference
Character, Graphic and UCS-2 Data
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... *
DName+++++++++++ETDsFrom+++To/L+++IDc.Functions++++++++++++++++++++++++++++
* Standalone fields:
D var5
S
5A
VARYING
D var10
S
10A
VARYING INZ('0123456789')
D max_len_a
S
32767A
VARYING
* Prerun-time array:
D arr1
S
100A
VARYING FROMFILE(dataf)
* Data structure subfields:
D ds1
DS
*
Subfield defined with length notation:
D
sf1_5
5A
VARYING
D
sf2_10
10A
VARYING INZ('0123456789')
*
Subfield defined using positional notation: A(5)VAR
D
sf4_5
101
107A
VARYING
*
Subfields showing internal representation of varying:
D
sf7_25
100A
VARYING
D
sf7_len
5I 0 OVERLAY(sf7_25:1)
D
sf7_data
100A
OVERLAY(sf7_25:3)
* Procedure prototype
D Replace
PR
32765A
VARYING
D
String
32765A
CONSTANT VARYING OPTIONS(*VARSIZE)
D
FromStr
32765A
CONSTANT VARYING OPTIONS(*VARSIZE)
D
ToStr
32765A
CONSTANT VARYING OPTIONS(*VARSIZE)
D
StartPos
5U 0 VALUE
D
Replaced
5U 0 OPTIONS(*OMIT)
Figure 81. Defining Variable-Length Character and UCS-2 Fields
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The following is an example of defining variable-length graphic and UCS-2 fields:
* .. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+...
DName+++++++++++ETDsFrom+++To/L+++IDc.Functions++++++++++++++++
*------------------------------------------------------------* Graphic fields
*------------------------------------------------------------* Standalone fields:
D GRA20
S
20G
VARYING
D MAX_LEN_G
S
16383G
VARYING
* Prerun-time array:
D ARR1
S
100G
VARYING FROMFILE(DATAF)
* Data structure subfields:
D DS1
DS
*
Subfield defined with length notation:
D
SF3_20
20G
VARYING
*
Subfield defined using positional notation: G(10)VAR
D
SF6_10
11
32G
VARYING
*------------------------------------------------------------*
UCS-2 fields
*------------------------------------------------------------D MAX_LEN_C
S
16383C
VARYING
D FLD1
S
5C
INZ(%UCS2('ABCDE')) VARYING
D FLD2
S
2C
INZ(U'01230123') VARYING
D FLD3
S
2C
INZ(*HIVAL) VARYING
D DS_C
DS
D
SF3_20_C
20C
VARYING
*
Subfield defined using positional notation: C(10)VAR
D
SF_110_C
11
32C
VARYING
Figure 82. Defining Variable-Length Graphic and UCS-2 Fields
Chapter 10. Data Types and Data Formats
167
Character, Graphic and UCS-2 Data
|
|
|
|
|
|
Using Variable-Length Fields
|
|
The following sections describe how to best use variable-length fields and how the
current length changes when using different operation codes.
|
|
|
|
How the Length of the Field is Set: When a variable-length field is initialized
using INZ, the initial length is set to be the length of the initialization value. For
example, if a character field of length 10 is initialized to the value 'ABC', the initial
length is set to 3.
|
|
The EVAL operation changes the length of a variable-length target. For example, if
a character field of length 10 is assigned the value 'XY', the length is set to 2.
The length part of a variable-length field represents the current length of the field
measured in characters. For character fields, this length also represents the current
length in bytes. For double-byte fields (graphic and UCS-2), this represents the
length of the field in double bytes. For example, a UCS-2 field with a current length
of 3 is 3 double-byte characters long, and 6 bytes long.
|
|
|
|
|
|
|
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D fld
10A
VARYING
* It does not matter what length 'fld' has before the
* EVAL; after the EVAL, the length will be 2.
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq...
C
EVAL
fld = 'XY'
|
|
|
|
The DSPLY operation changes the length of a variable-length result field to the
length of the value entered by the user. For example, if the result field is a character field of length 10, and the value entered by the user is '12345', the length of
the field will be set to 5 by the DSPLY operation.
|
The CLEAR operation changes the length of a variable-length field to 0.
|
|
The PARM operation sets the length of the result field to the length of the field in
Factor 2, if specified.
|
|
|
|
Fixed form operations MOVE, MOVEL, CAT, SUBST and XLATE do not change
the length of variable-length result fields. For example, if the value 'XYZ' is moved
using MOVE to a variable-length character field of length 10 whose current length
is 2, the length of the field will not change and the data will be truncated.
|
|
|
|
|
|
|
|
|
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D fld
10A
VARYING
* Assume fld has a length of 2 before the MOVEL.
* After the first MOVEL, it will have a value of 'XY'
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq...
C
MOVEL
'XYZ'
fld
* After the second MOVEL, it will have the value '1Y'
C
MOVEL
'1'
fld
|
|
Note: The recommended use for MOVE and MOVEL, as opposed to EVAL, is for
changing the value of fields that you want to be temporarily fixed in length.
168
ILE RPG for AS/400 Reference
Character, Graphic and UCS-2 Data
|
|
An example is building a report with columns whose size may vary from day
to day, but whose size should be fixed for any given run of the program.
|
|
When a field is read from a file (Input specifications), the length of a variable-length
field is set to the length of the input data.
|
|
The "Blank After" function of Output specifications sets the length of a variablelength field to 0.
|
|
You can set the length of a variable-length field yourself using the %LEN builtin
function on the left-hand-side of an EVAL operation.
|
|
|
How the Length of the Field is Used: When a variable-length field is used for its
value, its current length is used. For the following example, assume 'result' is a
fixed length field with a length of 7.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D fld
10A
VARYING
* For the following EVAL operation
*
Value of 'fld'
Length of 'fld'
'result'
*
-------------------------------------*
'ABC'
3
'ABCxxx '
*
'A'
1
'Axxx
'
*
''
0
'xxx
'
*
'ABCDEFGHIJ'
10
'ABCDEFG'
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq...
C
EVAL
result = fld + 'xxx'
* For the following MOVE operation, assume 'result'
* has the value '.......' before the MOVE.
*
Value of 'fld'
Length of 'fld'
'result'
*
-------------------------------------*
'ABC'
3
'....ABC'
*
'A'
1
'......A'
*
''
0
'.......'
*
'ABCDEFGHIJ'
10
'DEFGHIJ'
C
MOVE
fld
result
|
|
|
|
|
Why You Should Use Variable-Length Fields: Using variable-length fields for
temporary variables can improve the performance of string operations, as well as
making your code easier to read since you do not have to save the current length
of the field in another variable for %SUBST, or use %TRIM to ignore the extra
blanks.
|
|
|
|
|
If a subprocedure is meant to handle string data of different lengths, using variablelength fields for parameters and return values of prototyped procedures can
enhance both the performance and readability of your calls and your procedures.
You will not need to pass any length parameters or use CEEDOD within your
subrocedure to get the actual length of the parameter.
Chapter 10. Data Types and Data Formats
169
Character, Graphic and UCS-2 Data
CVTOPT(*VARCHAR) and CVTOPT(*VARGRAPHIC)
|
|
|
|
|
The ILE RPG compiler can internally define variable-length character, graphic, or
UCS-2 fields from an externally described file or data structure as fixed-length character fields. Although converting variable-length character, graphic, and UCS-2
fields to fixed-length format is not necessary, CVTOPT remains in the language to
support programs written before variable-length fields were supported.
You can convert variable-length fields by specifying *VARCHAR (for variable-length
character fields) or *VARGRAPHIC (for variable-length graphic or UCS-2 fields) on
the CVTOPT control specification keyword or command parameter. When
*VARCHAR or *VARGRAPHIC is not specified, or *NOVARCHAR or
*NOVARGRAPHIC is specified, variable-length fields are not converted to fixedlength character and can be used in your ILE RPG program as variable-length.
|
The following conditions apply when *VARCHAR or *VARGRAPHIC is specified:
¹ If a variable-length field is extracted from an externally described file or an
externally described data structure, it is declared in an ILE RPG program as a
fixed-length character field.
¹ For single-byte character fields, the length of the declared ILE RPG field is the
length of the DDS field plus 2 bytes.
¹ For DBCS-graphic data fields, the length of the declared ILE RPG field is twice
the length of the DDS field plus 2 bytes.
¹ The two extra bytes in the ILE RPG field contain a unsigned integer number
which represents the current length of the variable-length field. Figure 83
shows the ILE RPG field length of variable-length fields.
¹ For variable-length graphic fields defined as fixed-length character fields, the
length is double the number of graphic characters.
Single-byte character fields:
length
character-data
UNS(5)
CHAR(N)
N = declared length in DDS
2 + N = field length
Graphic data type fields:
length
graphic-data
UNS(5)
CHAR(2(N))
N = declared length in DDS = number of double bytes
2 + 2(N) = field length
Figure 83. ILE RPG Field Length of Converted Variable-Length Fields
170
ILE RPG for AS/400 Reference
Character, Graphic and UCS-2 Data
¹ Your ILE RPG program can perform any valid character calculation operations
on the declared fixed-length field. However, because of the structure of the
field, the first two bytes of the field must contain valid unsigned integer data
when the field is written to a file. An I/O exception error will occur for an output
operation if the first two bytes of the field contain invalid field-length data.
¹ Control-level indicators, match field entries, and field indicators are not allowed
on an input specification if the input field is a variable-length field from an
externally described input file.
¹ Sequential-within-limits processing is not allowed when a file contains variablelength key fields.
¹ Keyed operations are not allowed when factor 1 of a keyed operation corresponds to a variable-length key field in an externally described file.
¹ If you choose to selectively output certain fields in a record and the variablelength field is either not specified on the output specification or is ignored in the
ILE RPG program, the ILE RPG compiler will place a default value in the output
buffer of the newly added record. The default is 0 in the first two bytes and
blanks in all of the remaining bytes.
¹ If you want to change converted variable-length fields, ensure that the current
field length is correct. One way to do this is:
1. Define a data structure with the variable-length field name as a subfield
name.
2. Define a 5-digit unsigned integer subfield overlaying the beginning of the
field, and define an N-byte character subfield overlaying the field starting at
position 3.
3. Update the field.
Alternatively, you can move another variable-length field left-aligned into the
field. An example of how to change a converted variable-length field in an ILE
RPG program follows.
Chapter 10. Data Types and Data Formats
171
Character, Graphic and UCS-2 Data
*..1....+....2....+....3....+....4....+....5....+....6....+....7....+..
A*
A*
File MASTER contains a variable-length field
A*
AAN01N02N03T.Name++++++Rlen++TDpBLinPosFunctions+++++++++++++++++++++
A*
A
R REC
A
FLDVAR
100
VARLEN
*..1....+....2....+....3....+....4....+....5....+....6....+....7....+.. *
*
*
Specify the CVTOPT(*VARCHAR) keyword on a control
*
specification or compile the ILE RPG program with
*
CVTOPT(*VARCHAR) on the command.
*
HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*
H CVTOPT(*VARCHAR)
*
*
Externally described file name is MASTER.
*
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++
*
FMASTER
UF
E
DISK
*
*
FLDVAR is a variable-length field defined in DDS with
*
a DDS length of 100. Notice that the RPG field length
*
is 102.
*
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
*
D
DS
D FLDVAR
1
102
D
FLDLEN
5U 0 OVERLAY(FLDVAR:1)
D
FLDCHR
100
OVERLAY(FLDVAR:3)
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
*
* A character value is moved to the field FLDCHR.
* After the CHECKR operation, FLDLEN has a value of 5.
C
READ
MASTER
LR
C
MOVEL
'SALES'
FLDCHR
C
' '
CHECKR
FLDCHR
FLDLEN
C NLR
UPDATE
REC
Figure 84. Converting a Variable-Length Character Field
If you would like to use a converted variable-length graphic field, you can code a
2-byte unsigned integer field to hold the length, and a graphic subfield of length N
to hold the data portion of the field.
172
ILE RPG for AS/400 Reference
Character, Graphic and UCS-2 Data
*
*
Specify the CVTOPT(*VARGRAPHIC) keyword on a control
*
specification or compile the ILE RPG program with
*
CVTOPT(*VARGRAPHIC) on the command.
*
*
The variable-length graphic field VGRAPH is declared in the
*
DDS as length 3. This means the maximum length of the field
*
is 3 double bytes, or 6 bytes. The total length of the field,
*
counting the length portion, is 8 bytes.
*
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
*
D
DS
DVGRAPH
8
D VLEN
4U 0 OVERLAY(VGRAPH:1)
D VDATA
3G
OVERLAY(VGRAPH:3)
*
*
Assume GRPH is a fixed-length graphic field of length 2
*
double bytes. Copy GRPH into VGRAPH and set the length of
*
VGRAPH to 2.
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
C*
C
MOVEL
GRPH
VDATA
C
Z-ADD
2
VLEN
Figure 85. Converting a Variable-Length Graphic Field
|
|
|
|
|
Conversion between Character, Graphic and UCS-2 Data
Note: If graphic CCSIDs are ignored (CCSID(*GRAPH:*IGNORE) was specified
on the control specification or CCSID(*GRAPH) was not specified at all),
graphic data is not considered to have a CCSID and conversions are not
supported between graphic data and UCS-2 data.
|
|
Character, graphic, and UCS-2 data can have different CCSIDs (Coded Character
Set IDs). Conversion between these data types depends on the CCSID of the data.
|
|
|
|
CCSIDs of Data
|
|
When converting between character and graphic data, the CCSID of the character
data is assumed to be the graphic CCSID related to the job CCSID.
|
|
When converting between character and UCS-2 data, the CCSID of the character
data is assumed to be the mixed-byte CCSID related to the job CCSID.
|
|
|
|
|
The CCSID of UCS-2 data defaults to 13488. This default can be changed using
the CCSID(*UCS2) keyword on the Control specification. The CCSID for programdescribed UCS-2 fields can be specified using the CCSID keyword on the Definition
specification. The CCSID for externally-described UCS-2 fields comes from the
external file.
|
|
Note: UCS-2 fields are defined in DDS by specifying a data type of G and a
CCSID of 13488.
The CCSID of character data is only considered when converting between character and UCS-2 data or between character and graphic data (unless graphic
CCSIDs are being ignored).
Chapter 10. Data Types and Data Formats
173
Character, Graphic and UCS-2 Data
|
|
|
|
The CCSID of graphic data defaults to the value specified in the CCSID(*GRAPH)
keyword on the Control specification. The CCSID for program-described graphic
fields can be specified using the CCSID keyword on the Definition specification.
The CCSID for externally-described graphic fields comes from the external file.
|
|
|
|
Conversions
|
|
|
Additionally, graphic data and UCS-2 data can be converted from one CCSID to
another using the conversion operations and built-in functions, and also using EVAL
and when passing prototyped parameters.
|
|
|
Otherwise, UCS-2 fields, character fields and graphic fields, and UCS-2 fields or
graphic fields with different CCSIDs cannot be mixed in the same operation or
built-in function.
|
|
|
Conversion between character and double-byte graphic fields consists of adding or
removing shift-out and shift-in bracketing and possibly performing CCSID conversion on the graphic data.
Conversion between character, graphic, and UCS-2 data is supported using the
MOVE and MOVEL operations and the %CHAR, %GRAPH, and %UCS2 built-in
functions.
Alternate Collating Sequence
|
The alternate collating sequence applies only to single-byte character data.
Each character is represented internally by a hexadecimal value, which governs the
order (ascending or descending sequence) of the characters and is known as the
normal collating sequence. The alternate collating sequence function can be used
to alter the normal collating sequence. This function also can be used to allow two
or more characters to be considered equal.
Changing the Collating Sequence
Using an alternate collating sequence means modifying the collating sequence for
character match fields (file selection) and character comparisons. You specify that
an alternate collating sequence will be used by specifying the ALTSEQ keyword on
the control specification. The calculation operations affected by the alternate collating sequence are ANDxx, COMP, CABxx, CASxx, DOU, DOUxx, DOW, DOWxx,
IF, IFxx, ORxx, WHEN, and WHENxx. This does not apply to graphic or UCS-2
compare operations. LOOKUP and SORTA are affected only if you specify
ALTSEQ(*EXT). The characters are not permanently changed by the alternate collating sequence, but are temporarily altered until the matching field or character
compare operation is completed.
|
Use the ALTSEQ(*NONE) keyword on the definition specification for a variable to
indicate that when the variable is being compared with other character data, the
normal collating sequence should always be used even if an alternate collating
sequence was defined.
Changing the collating sequence does not affect the LOOKUP and SORTA operations (unless you specify ALTSEQ(*EXT)) or the hexadecimal values assigned to
the figurative constants *HIVAL and *LOVAL. However, changing the collating
sequence can affect the order of the values of *HIVAL and *LOVAL in the collating
sequence. Therefore, if you specify an alternate collating sequence in your program
174
ILE RPG for AS/400 Reference
Character, Graphic and UCS-2 Data
and thereby cause a change in the order of the values of *HIVAL and *LOVAL,
undesirable results may occur.
Using an External Collating Sequence
To specify that the values in the SRTSEQ and LANGID command parameters or
control specification keywords should be used to determine the alternate collating
sequence, specify ALTSEQ(*EXT) on the control specification. For example, if
ALTSEQ(*EXT) is used, and SRTSEQ(*LANGIDSHR) and LANGID(*JOBRUN) are
specified, then when the program is run, the shared-weight table for the user
running the program will be used as the alternate collating sequence.
Since the LOOKUP and SORTA operations are affected by the alternate collating
sequence when ALTSEQ(*EXT) is specified, character compile-time arrays and
tables are sequence-checked using the alternate collating sequence. If the actual
collating sequence is not known until runtime, the array and table sequence cannot
be checked until runtime. This means that you could get a runtime error saying that
a compile-time array or table is out of sequence.
Pre-run arrays and tables are also sequence-checked using the alternate collating
sequence when ALTSEQ(*EXT) is specified.
Note: The preceding discussion does not apply for any arrays and tables defined
with ALTSEQ(*NONE) on the definition specification.
Specifying an Alternate Collating Sequence in Your Source
To specify that an alternate collating sequence is to be used, use the
ALTSEQ(*SRC) keyword on the control specification. If you use the **ALTSEQ,
**CTDATA, and **FTRANS keywords in the compile-time data section, the
alternate-collating sequence data may be entered anywhere following the source
records. If you do not use those keywords, the sequence data must follow the
source records, and the file translation records but precede any compile-time array
data.
If a character is to be inserted between two consecutive characters, you must
specify every character that is altered by this insertion. For example, if the dollar
sign ($) is to be inserted between A and B, specify the changes for character B
onward.
See Appendix B, “EBCDIC Collating Sequence” on page 697 for the EBCDIC character set.
Formatting the Alternate Collating Sequence Records
The changes to the collating sequence must be transcribed into the correct record
format so that they can be entered into the system. The alternate collating
sequence must be formatted as follows:
Record
Position
Entry
1-6
ALTSEQ (This indicates to the system that the normal sequence is being
altered.)
7-10
Leave these positions blank.
11-12
Enter the hexadecimal value for the character whose normal sequence is
being changed.
Chapter 10. Data Types and Data Formats
175
Numeric Data Type
Record
Position
Entry
13-14
Enter the hexadecimal value of the character replacing the character
whose normal sequence is being changed.
15-18
19-22
23-26
...
77-80
All groups of four beginning with position 15 are used in the same manner
as positions 11 through 14. In the first two positions of a group enter the
hexadecimal value of the character to be replaced. In the last two positions enter the hexadecimal value of the character that replaces it.
The records that describe the alternate collating sequence must be preceded by a
record with **Ï (Ï = blank) in positions 1 through 3. The remaining positions in this
record can be used for comments.
HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
H ALTSEQ(*SRC)
DFLD1
s
4A
INZ('abcd')
DFLD2
s
4A
INZ('ABCD')
**
ALTSEQ
81C182C283C384C4
Numeric Data Type
The numeric data type represents numeric values. Numeric data has one of the
following formats:
¹ Binary
¹ Float
¹ Integer
¹ Packed-decimal
¹ Unsigned
¹ Zoned-decimal
The default initialization value for numeric fields is zero.
Binary Format
Binary format means that the sign (positive or negative) is in the leftmost bit of the
field and the numeric value is in the remaining bits of the field. Positive numbers
have a zero in the sign bit; negative numbers have a one in the sign bit and are in
twos complement form. A binary field can be from one to nine digits in length and
can be defined with decimal positions. If the length of the field is from one to four
digits, the compiler assumes a binary field length of 2 bytes. If the length of the
field is from five to nine digits, the compiler assumes a binary field length of 4
bytes.
176
ILE RPG for AS/400 Reference
Numeric Data Type
Processing of a Program-Described Binary Input Field
Every input field read in binary format is assigned a field length (number of digits)
by the compiler. A length of 4 is assigned to a 2-byte binary field; a length of 9 is
assigned to a 4-byte binary field, if the field is not defined elsewhere in the
program. Because of these length restrictions, the highest decimal value that can
be assigned to a 2-byte binary field is 9999 and the highest decimal value that can
be assigned to a 4-byte binary field is 999 999 999. In general, a binary field of n
digits can have a maximum value of n 9s. This discussion assumes zero decimal
positions.
Because a 2-byte field in binary format is converted by the compiler to a decimal
field with 1 to 4 digits, the input value may be too large. If it is, the leftmost digit of
the number is dropped. For example, if a four digit binary input field has a binary
value of hexadecimal 6000, the compiler converts this to 24 576 in decimal. The 2
is dropped and the result is 4576. Similarly, the input value may be too large for a
4-byte field in binary format. If the binary fields have zero (0) decimal positions,
then you can avoid this conversion problem by defining integer fields instead of
binary fields.
Note: Binary input fields cannot be defined as match or control fields.
Processing of an Externally Described Binary Input Field
The number of digits of a binary field is exactly the same as the length in the DDS
description. For example, if you define a binary field in your DDS specification as
having 7 digits and 0 decimal positions, the RPG IVcompiler handles the data like
this:
1. The field is defined as a 4-byte binary field in the input specification
2. A Packed(7,0) field is generated for the field in the RPG IV program.
If you want to retain the complete binary field information, redefine the field as a
binary subfield in a data structure or as a binary stand-alone field.
Note that an externally described binary field may have a value outside of the
range allowed by RPG IV binary fields. If the externally described binary field has
zero (0) decimal positions then you can avoid this problem. To do so, you define
the externally described binary field on a definition specification and specify the
EXTBININT keyword on the control specification. This will change the external
format of the externally described field to that of a signed integer.
Float Format
The float format consists of two parts:
¹ the mantissa and
¹ the exponent.
The value of a floating-point field is the result of multiplying the mantissa by 10
raised to the power of the exponent. For example, if 1.2345 is the mantissa and 5
is the exponent then the value of the floating-point field is:
1.2345 * (10 ** 5) = 123450
You define a floating-point field by specifying F in the data type entry of the appropriate specification.
Chapter 10. Data Types and Data Formats
177
Numeric Data Type
The decimal positions must be left blank. However, floating-point fields are considered to have decimal positions. As a result, float variables may not be used in any
place where a numeric value without decimal places is required, such as an array
index, do loop index, etc.
The default initialization and CLEAR value for a floating point field is 0E0.
The length of a floating point field is defined in terms of the number of bytes. It
must be specified as either 4 or 8 bytes. The range of values allowed for a positive
floating-point field are:
Field length
Minimum Allowed Value
Maximum Allowed Value
4 bytes
1.175 494 4 E-38
3.402 823 5 E+38
8 bytes
2.225 073 858 507 201 E-308
1.797 693 134 862 315 E+308
Note: Negative values have the same range, but with a negative sign.
Float variables conform to the IEEE standard as supported by the AS/400.
Since float variables are intended to represent "scientific" values, a numeric
value stored in a float variable may not represent the exact same value as it
would in a packed variable. Float should not be used when you need to
represent numbers exactly to a specific number of decimal places, such as
monetary amounts.
External Display Representation of a Floating-Point Field
See “Specifying an External Format for a Numeric Field” on page 160 for a general
description of external display representation.
The external display representation of float values applies for the following:
¹ Output of float data with Data-Format entry blank.
¹ Input of float data with Data-Format entry blank.
¹ External format of compile-time and prerun-time arrays and tables (when
keyword EXTFMT is omitted).
¹ Display and input of float values using operation code DSPLY.
¹ Output of float values on a dump listing.
¹ Result of built-in function %EDITFLT.
Output: When outputting float values, the external representation uses a format
similar to float literals, except that:
¹ Values are always written with the character E and the signs for both mantissa
and exponent.
¹ Values are either 14 or 23 characters long (for 4F and 8F respectively).
¹ Values are normalized. That is, the decimal point immediately follows the most
significant digit.
¹ The decimal separator character is either period or comma depending on the
parameter for Control Specification keyword DECEDIT.
Here are some examples of how float values are presented:
178
ILE RPG for AS/400 Reference
Numeric Data Type
+1.2345678E-23
-8.2745739E+03
-5.722748027467392E-123
+1,2857638E+14
if DECEDIT(',') is specified
Input: When inputting float values, the value is specified just like a float literal.
The value does not have to be normalized or adjusted in the field. When float
values are defined as array/table initialization data, they are specified in fields either
14 or 23 characters long (for 4F and 8F respectively). See "Float Numeric Literals"
on page 4 for more details.
Note the following about float fields:
¹ Alignment of float fields may be desired to improve the performance of
accessing float subfields. You can use the ALIGN keyword to align float subfields defined on a definition specification. 4-byte float subfields are aligned on
a 4-byte boundary and 8-byte float subfields are aligned along a 8-byte
boundary. For more information on aligning float subfields, see “ALIGN” on
page 280.
¹ Length adjustment is not allowed when the LIKE keyword is used to define a
field like a float field.
¹ Float input fields cannot be defined as match or control fields.
Integer Format
The integer format is similar to the binary format with two exceptions:
¹ The integer format allows the full range of binary values
¹ The number of decimal positions for an integer field is always zero.
You define an integer field by specifying I in the Data-Type entry of the appropriate
specification. You can also define an integer field using the LIKE keyword on a
definition specification where the parameter is an integer field.
|
|
|
|
The length of an integer field is defined in terms of number of digits; it can be 3, 5,
10, or 20 digits long. A 3-digit field takes up 1 byte of storage; a 5-digit field takes
up 2 bytes of storage; a 10-digit field takes up 4 bytes; a 20-digit field takes up 8
bytes. The range of values allowed for an integer field depends on its length.
Field length
|
Range of Allowed Values
3-digit integer -128 to 127
5-digit integer -32768 to 32767
10-digit integer
-2147483648 to 2147483647
|
|
20-digit integer
-9223372036854775808 to 9223372036854775807
Note the following about integer fields:
¹ Alignment of integer fields may be desired to improve the performance of
accessing integer subfields. You can use the ALIGN keyword to align integer
subfields defined on a definition specification.
|
|
2-byte integer subfields are aligned on a 2-byte boundary; 4-byte integer subfields are aligned along a 4-byte boundary; 8-byte integer subfields are aligned
Chapter 10. Data Types and Data Formats
179
Numeric Data Type
|
|
along an 8-byte boundary. For more information on aligning integer subfields,
see “ALIGN” on page 280.
|
|
|
¹ If the LIKE keyword is used to define a field like an integer field, the Length
entry may contain a length adjustment in terms of number of digits. The adjustment value must be such that the resulting number of digits for the field is 3, 5,
10, or 20.
¹ Integer input fields cannot be defined as match or control fields.
Packed-Decimal Format
Packed-decimal format means that each byte of storage (except for the low order
byte) can contain two decimal numbers. The low-order byte contains one digit in
the leftmost portion and the sign (positive or negative) in the rightmost portion. The
standard signs are used: hexadecimal F for positive numbers and hexadecimal D
for negative numbers. The packed-decimal format looks like this:
70
0
Digit
Digit
Digit
7
Sign
Byte
Figure 86. Packed-Decimal Format
The sign portion of the low-order byte indicates whether the numeric value represented in the digit portions is positive or negative. Figure 88 on page 184 shows
what the decimal number 21544 looks like in packed-decimal format.
Determining the Digit Length of a Packed-Decimal Field
Use the following formula to find the length in digits of a packed-decimal field:
Number of digits = 2n – 1,
...where n = number of packed input record positions used.
This formula gives you the maximum number of digits you can represent in packeddecimal format; the upper limit is 30.
Packed fields can be up to 16 bytes long. Table 12 shows the packed equivalents
for zoned-decimal fields up to 30 digits long:
Table 12. Packed Equivalents for Zoned-Decimal Fields up to 30 Digits Long
180
Zoned-Decimal
Length in Digits
Number of Bytes
Used in Packed-Decimal Field
1
1
2, 3
2
4, 5
3
.
.
.
.
.
.
.
.
.
28, 29
15
30
16
ILE RPG for AS/400 Reference
Numeric Data Type
Note: Only 30 digits are allowed. If you use positional notation for 16-byte packed
fields, you must use the PACKEVEN keyword or otherwise define the field
as having 30 digits.
For example, an input field read in packed-decimal format has a length of five bytes
(as specified on the input or definition specifications). The number of digits in this
field equals 2(5) − 1 or 9. Therefore, when the field is used in the calculation specifications, the result field must be nine positions long. The “PACKEVEN” on
page 302 keyword on the definition specification can be used to indicate which of
the two possible sizes you want when you specify a packed field using from and to
positions rather than number of digits.
Unsigned Format
The unsigned integer format is like the integer format except that the range of
values does not include negative numbers. You should use the unsigned format
only when non-negative integer data is expected.
You define an unsigned field by specifying U in the Data-Type entry of the appropriate specification. You can also define an unsigned field using the LIKE keyword
on the definition specification where the parameter is an unsigned field.
|
|
|
|
The length of an unsigned field is defined in terms of number of digits; it can be 3,
5, 10, or 20 digits long. A 3-digit field takes up 1 byte of storage; a 5-digit field
takes up 2 bytes of storage; a 10-digit field takes up 4 bytes;a 20-digit field takes
up 8 bytes. The range of values allowed for an unsigned field depends on its
length.
Field length
|
|
Range of Allowed Values
3-digit unsigned
0 to 255
5-digit unsigned
0 to 65535
10-digit unsigned
0 to 4294967295
|
|
20-digit unsigned
0 to 18446744073709551615
For other considerations regarding the use of unsigned fields, including information
on alignment, see “Integer Format” on page 179.
Zoned-Decimal Format
Zoned-decimal format means that each byte of storage can contain one digit or one
character. In the zoned-decimal format, each byte of storage is divided into two
portions: a 4-bit zone portion and a 4-bit digit portion. The zoned-decimal format
looks like this:
Chapter 10. Data Types and Data Formats
181
Numeric Data Type
70
0
Zone
Digit
70
7 0
Zone
Digit
Zone
Digit
Zone
7 0
Digit
Zone
7
Digit
Byte
1 1 0 1 = Minus sign (hex D)
1 1 1 1 = Plus sign (hex F)
Figure 87. Zoned-Decimal Format
The zone portion of the low-order byte indicates the sign (positive or negative) of
the decimal number. The standard signs are used: hexadecimal F for positive
numbers and hexadecimal D for negative numbers. In zoned-decimal format, each
digit in a decimal number includes a zone portion; however, only the low-order zone
portion serves as the sign. Figure 88 on page 184 shows what the number 21544
looks like in zoned-decimal format.
You must consider the change in field length when coding the end position in positions 40 through 43 of the Output specifications and the field is to be output in
packed format. To find the length of the field after it has been packed, use the
following formula:
n
Field length =
+ 1
2
. . . where n = number of digits in the zoned decimal field.
(Any remainder from the division is ignored.)
You can specify an alternative sign format for zoned-decimal format. In the alternative sign format, the numeric field is immediately preceded or followed by a + or −
sign. A plus sign is a hexadecimal 4E, and a minus sign is a hexadecimal 60.
When an alternative sign format is specified, the field length (specified on the input
specification) must include an additional position for the sign. For example, if a
field is 5 digits long and the alternative sign format is specified, a field length of 6
positions must be specified.
Considerations for Using Numeric Formats
Keep in mind the following when defining numeric fields:
¹ When coding the end position in positions 47 through 51 of the output specifications, be sure to use the external format when calculating the number of
bytes to be occupied by the output field. For example, a packed field with 5
digits is stored in 3 bytes, but when output in zoned format, it requires 5 bytes.
When output in integer format, it only requires 2 bytes.
¹ If you move a character field to a zoned numeric, the sign of the character field
is fixed to zoned positive or zoned negative. The zoned portion of the other
bytes will be forced to 'F'. However, if the digit portion of one of the bytes in the
character field does not contain a valid digit a decimal data error will occur.
¹ When numeric fields are written out with no editing, the sign is not printed as a
separate character; the last digit of the number will include the sign. This can
182
ILE RPG for AS/400 Reference
Numeric Data Type
produce surprising results; for example, when -625 is written out, the zoned
decimal value is X'F6F2D5' which appears as 62N.
Guidelines for Choosing the Numeric Format for a Field
You should specify the integer or unsigned format for fields when:
¹ Performance of arithmetic is important
With certain arithmetic operations, it may be important that the value used be
an integer. Some examples where performance may be improved include array
index computations and arguments for the built-in function %SUBST.
¹ Interacting with routines written in other languages that support an integer data
type, such as ILE C.
¹ Using fields in file feedback areas that are defined as integer and that may
contain values above 9999 or 999999999.
Packed, zoned, and binary formats should be specified for fields when:
¹ Using values that have implied decimal positions, such currency values
|
¹ Manipulating values having more than 19 digits
¹ Ensuring a specific number of digits for a field is important
Float format should be specified for fields when:
¹ The same variable is needed to hold very small and/or very large values that
cannot be represented in packed or zoned values.
Note: Overflow is more likely to occur with arithmetic operations performed using
the integer or unsigned format, especially when integer arithmetic occurs in
free-form expressions. This is because the intermediate results are kept in
integer or unsigned format rather than a temporary decimal field of sufficient
size.
Representation of Numeric Formats
Figure 88 on page 184 shows what the decimal number 21544 looks like in
various formats.
Chapter 10. Data Types and Data Formats
183
Numeric Data Type
Packed Decimal Format:
Positive Sign
2
0010
1
5
4
0001 0101 0010
4
0010 1111
3 bytes
Zoned Decimal Format:
Zone
Zone
2
1111 0010
Zone
5
1
1111 0001
Zone
1111 0101
Positive Sign
4
1111 0100
4
1111 0100
5 bytes
Binary Format:
16384
+ 4096
+ 1024
+
32
+
8
------------21544
Positive
Sign
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 1 0 1
0 1 0 0
0 0 1 0
4 bytes
Integer (Signed) Format:
16384
+ 4096
+ 1024
+
32
+
8
------------21544
Positive
Sign
0 1 0 1
0 1 0 0
0 0 1 0
1 0 0 0
2 bytes
Unsigned Format:
16384
+ 4096
+ 1024
+
32
+
8
------------21544
0 1 0 1
0 1 0 0
0 0 1 0
1 0 0 0
2 bytes
Figure 88. Representation of the Number 21544 in each of the Numeric Formats
Note the following about the representations in the figure.
184
ILE RPG for AS/400 Reference
1 0 0 0
Date Data Type
¹ To obtain the numeric value of a positive binary or integer number, unsigned
number, add the values of the bits that are on (1), but do not include the sign
bit (if present). For an unsigned number, add the values of the bits that are on,
including the leftmost bit.
¹ The value 21544 cannot be represented in a 2-byte binary field even though it
only uses bits in the low-order two bytes. A 2-byte binary field can only hold up
to 4 digits, and 21544 has 5 digits.
Figure 89 shows the number -21544 in integer format.
Negative Sign
1 0 1 0
1 0 1 1
1 1 0 1
1 0 0 0
2 bytes
Figure 89. Integer Representation of the Number -21544
Date Data Type
Date fields have a predetermined size and format. They can be defined on the definition specification. Leading and trailing zeros are required for all date data.
Date constants or variables used in comparisons or assignments do not have to be
in the same format or use the same separators. Also, dates used for I/O operations
such as input fields, output fields or key fields are also converted (if required) to the
necessary format for the operation.
The default internal format for date variables is *ISO. This default internal format
can be overridden globally by the control specification keyword DATFMT and individually by the definition specification keyword DATFMT.
The hierarchy used when determining the internal date format and separator for a
date field is
1. From the DATFMT keyword specified on the definition specification
2. From the DATFMT keyword specified on the control specification
3. *ISO
There are three kinds of date data formats, depending on the range of years that
can be represented. This leads to the possibility of a date overflow or underflow
condition occurring when the result of an operation is a date outside the valid range
for the target field. The formats and ranges are as follows:
Number of Digits in Year
Range of Years
2 (*YMD, *DMY, *MDY, *JUL)
1940 to 2039
3 (*CYMD, *CDMY, *CMDY)
1900 to 2899
4 (*ISO, *USA, *EUR, *JIS, *LONGJUL)
0001 to 9999
Chapter 10. Data Types and Data Formats
185
Date Data Type
Table 13 on page 186 lists the RPG-defined formats for date data and their separators.
For examples on how to code date fields, see the examples in:
¹ “Date Operations” on page 445
¹ “Moving Date-Time Data” on page 454
¹ “ADDDUR (Add Duration)” on page 470
¹ “MOVE (Move)” on page 566
¹ “EXTRCT (Extract Date/Time/Timestamp)” on page 537
¹ “SUBDUR (Subtract Duration)” on page 661
¹ “TEST (Test Date/Time/Timestamp)” on page 668
Table 13. RPG-defined date formats and separators for Date data type
Format
Name
Description
Format (Default
Separator)
Valid Separators
Length
Example
2-Digit Year Formats
*MDY
Month/Day/Year
mm/dd/yy
/ - . , '&'
8
01/15/96
*DMY
Day/Month/Year
dd/mm/yy
/ - . , '&'
8
15/01/96
*YMD
Year/Month/Day
yy/mm/dd
/ - . , '&'
8
96/01/15
*JUL
Julian
yy/ddd
/ - . , '&'
6
96/015
4-Digit Year Formats
*ISO
International Standards
Organization
yyyy-mm-dd
-
10
1996-01-15
*USA
IBM USA Standard
mm/dd/yyyy
/
10
01/15/1996
*EUR
IBM European
Standard
dd.mm.yyyy
.
10
15.01.1996
*JIS
Japanese Industrial
Standard Christian Era
yyyy-mm-dd
-
10
1996-01-15
Table 14 lists the *LOVAL, *HIVAL, and default values for all the RPG-defined date
formats.
Table 14 (Page 1 of 2). Date Values
Format name
Description
*LOVAL
*HIVAL
Default Value
2-Digit Year Formats
*MDY
Month/Day/Year
01/01/40
12/31/39
01/01/40
*DMY
Day/Month/Year
01/01/40
31/12/39
01/01/40
*YMD
Year/Month/Day
40/01/01
39/12/31
40/01/01
*JUL
Julian
40/001
39/365
40/001
4-Digit Year Formats
*ISO
International Standards Organization
0001-01-01
9999-12-31
0001-01-01
*USA
IBM USA Standard
01/01/0001
12/31/9999
01/01/0001
186
ILE RPG for AS/400 Reference
Date Data Type
Table 14 (Page 2 of 2). Date Values
Format name
Description
*LOVAL
*HIVAL
Default Value
*EUR
IBM European Standard
01.01.0001
31.12.9999
01.01.0001
*JIS
Japanese Industrial Standard
Christian Era
0001-01-01
9999-12-31
0001-01-01
Several formats are also supported for fields used by the MOVE, MOVEL, and
TEST operations only. This support is provided for compatibility with externally
defined values that are already in a 3-digit year format and the 4-digit year
*LONGJUL format. It also applies to the 2-digit year formats when *JOBRUN is
specified.
*JOBRUN should be used when the field which it is describing is known to have the
attributes from the job. For instance, a 12-digit numeric result of a TIME operation
will be in the job date format.
Table 15 lists the valid externally defined date formats that can be used in Factor 1
of a MOVE, MOVEL, and TEST operation.
Table 15. Externally defined date formats and separators
Format Name
Description
Format (Default
Separator)
Valid Separators
Length
Example
2-Digit Year Formats
*JOBRUN1
Determined at runtime from the DATFMT, or DATSEP job values.
3-Digit Year Formats2
*CYMD
Century
Year/Month/Day
cyy/mm/dd
/ - . , '&'
9
101/04/25
*CMDY
Century
Month/Day/Year
cmm/dd/yy
/ - . , '&'
9
104/25/01
*CDMY
Century
Day/Month/Year
cdd/mm/yy
/ - . , '&'
9
125/04/01
yyyy/ddd
/ - . , '&'
8
2001/115
4-Digit Year Formats
*LONGJUL
Long Julian
Notes:
1. *JOBRUN is valid only for character or numeric dates with a 2-digit year since the run-time job attribute for
DATFMT can only be *MDY, *YMD, *DMY or *JUL.
2. Valid values for the century character 'c' are:
'c'
Years
----------------------0
1900-1999
1
2000-2099
.
.
.
.
.
.
9
2800-2899
Chapter 10. Data Types and Data Formats
187
Time Data Type
Separators
When coding a date format on a MOVE, MOVEL or TEST operation, separators are
optional for character fields. To indicate that there are no separators, specify the
format followed by a zero. For more information on how to code date formats
without separators see “MOVE (Move)” on page 566, “MOVEL (Move Left)” on
page 586 and “TEST (Test Date/Time/Timestamp)” on page 668.
Initialization
To initialize the Date field to the system date at runtime, specify INZ(*SYS) on the
definition specification. To initialize the Date field to the job date at runtime, specify
INZ(*JOB) on the definition specification. *SYS or *JOB cannot be used with a field
that is exported. The Date field can also be initialized to a literal, named constant or
figurative constant.
Note: Runtime initialization takes place after static intitialization.
Time Data Type
Time fields have a predetermined size and format. They can be defined on the definition specification. Leading and trailing zeros are required for all time data.
Time constants or variables used in comparisons or assignments do not have to be
in the same format or use the same separators. Also, times used for I/O operations
such as input fields, output fields or key fields are also converted (if required) to the
necessary format for the operation.
The default internal format for time variables is *ISO. This default internal format
can be overridden globally by the control specification keyword TIMFMT and individually by the definition specification keyword TIMFMT.
The hierarchy used when determining the internal time format and separator for a
time field is
1. From the TIMFMT keyword specified on the definition specification
2. From the TIMFMT keyword specified on the control specification
3. *ISO
For examples on how to code time fields, see the examples in:
¹ “Date Operations” on page 445
¹ “Moving Date-Time Data” on page 454
¹ “ADDDUR (Add Duration)” on page 470
¹ “MOVE (Move)” on page 566
¹ “SUBDUR (Subtract Duration)” on page 661
¹ “TEST (Test Date/Time/Timestamp)” on page 668
Table 16 on page 189 shows the time formats supported and their separators.
188
ILE RPG for AS/400 Reference
Time Data Type
Table 16. Time formats and separators for Time data type
RPG
Format
Name
Description
Format
(Default
Separator)
Valid
Separators
Length
Example
*HMS
Hours:Minutes:Seconds
hh:mm:ss
:.,&
8
14:00:00
*ISO
International Standards Organization
hh.mm.ss
.
8
14.00.00
*USA
IBM USA Standard. AM and PM can be
any mix of upper and lower case.
hh:mm AM
or hh:mm
PM
:
8
02:00 PM
*EUR
IBM European Standard
hh.mm.ss
.
8
14.00.00
*JIS
Japanese Industrial Standard Christian Era
hh:mm:ss
:
8
14:00:00
Table 17 lists the *LOVAL, *HIVAL, and default values for all the time formats.
Table 17. Time Values
RPG
Format
Name
Description
*LOVAL
*HIVAL
Default
Value
*HMS
Hours:Minutes:Seconds
00:00:00
24:00:00
00:00:00
*ISO
International Standards Organization
00.00.00
24.00.00
00.00.00
*USA
IBM USA Standard. AM and PM can be any
mix of upper and lower case.
00:00 AM
12:00 AM
00:00 AM
*EUR
IBM European Standard
00.00.00
24.00.00
00.00.00
*JIS
Japanese Industrial Standard Christian Era
00:00:00
24:00:00
00:00:00
Separators
When coding a time format on a MOVE, MOVEL or TEST operation, separators are
optional for character fields. To indicate that there are no separators, specify the
format followed by a zero. For more information on how to code time formats
without separators see “MOVE (Move)” on page 566.
Initialization
To initialize the Time field to the system time at runtime, specify INZ(*SYS) on the
definition specification. *SYS cannot be used with a field that is exported. The Time
field can also be initialized at runtime to a literal, named constant or figurative constant.
Note: Runtime initialization takes place after static intitialization.
*JOBRUN
A special value of *JOBRUN can be used in Factor 1 of a MOVE, MOVEL or TEST
operation. This indicates that the separator of the field being described is based on
the run-time job attributes, TIMSEP.
Chapter 10. Data Types and Data Formats
189
Basing Pointer Data Type
Timestamp Data Type
Timestamp fields have a predetermined size and format. They can be defined on
the definition specification. Timestamp data must be in the format
yyyy-mm-dd-hh.mm.ss.mmmmmm (length 26).
Microseconds (.mmmmmm) are optional for timestamp literals and if not provided
will be padded on the right with zeros. Leading zeros are required for all timestamp
data.
The default initialization value for a timestamp is midnight of January 1, 0001
(0001-01-01-00.00.00.000000). The *HIVAL value for a timestamp is
9999-12-31-24.00.00.000000. The *LOVAL value for timestamp is
0001-01-01-00.00.00.000000.
For examples on how to code timestamp fields, see the examples in
¹ “Date Operations” on page 445
¹ “Moving Date-Time Data” on page 454
¹ “ADDDUR (Add Duration)” on page 470
¹ “MOVE (Move)” on page 566
¹ “SUBDUR (Subtract Duration)” on page 661
Separators
When coding the timestamp format on a MOVE, MOVEL or TEST operation, separators are optional for character fields. To indicate that there are no separators,
specify *ISO0. For an example of how *ISO is used without separators see “TEST
(Test Date/Time/Timestamp)” on page 668.
Initialization
To initialize the Timestamp field to the system date at runtime, specify INZ(*SYS)
on the definition specification. *SYS cannot be used with a field that is exported.
The Timestamp field can also be initialized at runtime to a literal, named constant
or figurative constant.
Note: Runtime initialization takes place after static intitialization.
Basing Pointer Data Type
|
|
|
|
Basing pointers are used to locate the storage for based variables. The storage is
accessed by defining a field, array, or data structure as based on a particular
basing pointer variable and setting the basing pointer variable to point to the
required storage location.
|
|
|
|
For example, consider the based variable MY_FIELD, a character field of length 5,
which is based on the pointer PTR1. The based variable does not have a fixed
location in storage. You must use a pointer to indicate the current location of the
storage for the variable.
|
Suppose that the following is the layout of some area of storage:
190
ILE RPG for AS/400 Reference
Basing Pointer Data Type
|
|
|
------------------------------------------------------------| A | B | C | D | E | F | G | H | I | J | K | L | M | N | O |
-------------------------------------------------------------
|
If we set pointer PTR1 to point to the G,
|
|
|
|
|
|
PTR1-------------------.
|
V
------------------------------------------------------------| A | B | C | D | E | F | G | H | I | J | K | L | M | N | O |
-------------------------------------------------------------
|
|
MY_FIELD is now located in storage starting at the 'G', so its value is 'GHIJK'. If
the pointer is moved to point to the 'J', the value of MY_FIELD becomes 'JKLMN':
|
|
|
|
|
|
PTR1-------------------.
|
V
------------------------------------------------------------| A | B | C | D | E | F | G | H | I | J | K | L | M | N | O |
-------------------------------------------------------------
|
|
If MY_FIELD is now changed by an EVAL statement to 'HELLO', the storage
starting at the 'J' would change:
|
|
|
|
|
|
PTR1-------------------.
|
V
------------------------------------------------------------| A | B | C | D | E | F | G | H | I | H | E | L | L | O | O |
-------------------------------------------------------------
Use the BASED keyword on the definition specification (see
“BASED(basing_pointer_name)” on page 282) to define a basing pointer for a field.
Basing pointers have the same scope as the based field.
The length of the basing pointer field must be 16 bytes long and must be aligned
on a 16 byte boundary. This requirement for boundary alignment can cause a
pointer subfield of a data structure not to follow the preceding field directly, and can
cause multiple occurrence data structures to have non-contiguous occurrences. For
more information on the alignment of subfields, see “Aligning Data Structure
Subfields” on page 125.
The default initialization value for basing pointers is *NULL.
Note: When coding basing pointers, you must be sure that you set the pointer to
storage that is large enough and of the correct type for the based field.
Figure 94 on page 196 shows some examples of how not to code basing
pointers.
Note: You can add or subtract an offset from a pointer in an expression, for
example EVAL ptr = ptr + offset. When doing pointer arithmetic be aware
that it is your responsibility to ensure that you are still pointing within the
storage of the item you are pointing to. In most cases no exception will be
issued if you point before or after the item.
When subtracting two pointers to determine the offset between them, the
pointers must be pointing to the same space, or the same type of storage.
For example, you can subtract two pointers in static storage, or two pointers
in automatic storage, or two pointers within the same user space.
Chapter 10. Data Types and Data Formats
191
Basing Pointer Data Type
|
|
|
Setting a Basing Pointer
You set or change the location of the based variable by setting or changing the
basing pointer in one of the following ways:
|
¹ Initializing with INZ(%ADDR(FLD)) where FLD is a non-based variable
|
¹ Assigning the pointer to the result of %ADDR(X) where X is any variable
|
¹ Assigning the pointer to the value of another pointer
|
|
|
¹ Using ALLOC or REALLOC (see “ALLOC (Allocate Storage)” on page 472,
“REALLOC (Reallocate Storage with New Length)” on page 628, and the ILE
RPG for AS/400 Programmer's Guide for examples)
|
¹ Moving the pointer forward or backward in storage using pointer arithmetic:
|
EVAL
|
("offset" is the distance in bytes that the pointer is moved)
PTR = PTR + offset
Examples
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
*
* Define a based data structure, array and field.
* If PTR1 is not defined, it will be implicitly defined
* by the compiler.
*
* Note that before these based fields or structures can be used,
* the basing pointer must be set to point to the correct storage
* location.
*
D DSbased
DS
BASED(PTR1)
D
Field1
1 16A
D
Field2
2
D
D ARRAY
S
20A
DIM(12) BASED(PRT2)
D
D Temp_fld
S
*
BASED(PRT3)
D
D PTR2
S
*
INZ
D PTR3
S
*
INZ(*NULL)
Figure 90. Defining based structures and fields
The following shows how you can add and subtract offsets from pointers and also
determine the difference in offsets between two pointers.
192
ILE RPG for AS/400 Reference
Basing Pointer Data Type
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+...8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
*
D P1
s
*
D P2
s
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
CL0N01++++++++++++++Opcode(E)+Extended Factor 2++++++++++++++++++++++++++++
*
* Allocate 20 bytes of storage for pointer P1.
C
ALLOC
20
P1
* Initialize the storage to 'abcdefghij'
C
EVAL
%STR(P1:20) = 'abcdefghij'
* Set P2 to point to the 9th byte of this storage.
C
EVAL
P2 = P1 + 8
* Show that P2 is pointing at 'i'. %STR returns the data that
* the pointer is pointing to up to but not incuding the first
* null-terminator x'00' that it finds, but it only searches for
* the given length, which is 1 in this case.
C
EVAL
Result = %STR(P2:1)
C
DSPLY
Result
1
* Set P2 to point to the previous byte
C
EVAL
P2 = P2 - 1
* Show that P2 is pointing at 'h'
C
EVAL
Result = %STR(P2:1)
C
DSPLY
Result
* Find out how far P1 and P2 are apart. (7 bytes)
C
EVAL
Diff = P2 - P1
C
DSPLY
Diff
5 0
* Free P1's storage
C
DEALLOC
P1
C
RETURN
Figure 91. Pointer Arithmetic
Figure 92 shows how to obtain the number of days in Julian format, if the Julian
date is required.
*..1....+....2....+....3....+....4....+....5....+....6....+....7....+....
HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
H DATFMT(*JUL)
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
*
D JulDate
S
D
INZ(D'95/177')
D
DATFMT(*JUL)
D JulDS
DS
BASED(JulPTR)
D Jul_yy
2 0
D Jul_sep
1
D Jul_ddd
3 0
D JulDay
S
3 0
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
CL0N01++++++++++++++Opcode(E)+Extended Factor 2++++++++++++++++++++++++++++
*
* Set the basing pointer for the structure overlaying the
* Julian date.
C
EVAL
JulPTR = %ADDR(JulDate)
* Extract the day portion of the Julian date
C
EVAL
JulDay = Jul_ddd
Figure 92. Obtaining a Julian Date
Chapter 10. Data Types and Data Formats
193
Basing Pointer Data Type
Figure 93 on page 194 illustrates the use of pointers, based structures and system
APIs. This program does the following:
1. Receives the Library and File name you wish to process
2. Creates a User space using the QUSCRTUS API
3. Calls an API (QUSLMBR) to list the members in the requested file
4. Gets a pointer to the User space using the QUSPTRUS API
5. Displays a message with the number of members and the name of the first and
last member in the file
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
*
D SPACENAME
DS
D
10
INZ('LISTSPACE')
D
10
INZ('QTEMP')
D ATTRIBUTE
S
10
INZ('LSTMBR')
D INIT_SIZE
S
9B 0 INZ(9999999)
D AUTHORITY
S
10
INZ('*CHANGE')
D TEXT
S
50
INZ('File member space')
D SPACE
DS
BASED(PTR)
D SP1
32767
*
* ARR is used with OFFSET to access the beginning of the
* member information in SP1
*
D ARR
1
OVERLAY(SP1) DIM(32767)
*
* OFFSET is pointing to start of the member information in SP1
*
D OFFSET
9B 0 OVERLAY(SP1:125)
*
* Size has number of member names retrieved
*
D SIZE
9B 0 OVERLAY(SP1:133)
D MBRPTR
S
*
D MBRARR
S
10
BASED(MBRPTR) DIM(32767)
D PTR
S
*
D FILE_LIB
S
20
D FILE
S
10
D LIB
S
10
D WHICHMBR
S
10
INZ('*ALL
')
D OVERRIDE
S
1
INZ('1')
D FIRST_LAST
S
50
INZ('
MEMBERS, +
D
FIRST =
, +
D
LAST =
')
D IGNERR
DS
D
9B 0 INZ(15)
D
9B 0
D
7A
Figure 93 (Part 1 of 2). Example of using pointers and based structures with an API
194
ILE RPG for AS/400 Reference
Basing Pointer Data Type
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
CL0N01++++++++++++++Opcode(E)+Extended Factor 2++++++++++++++++++++++++++++
*
* Receive file and library you want to process
*
C
*ENTRY
PLIST
C
FILE
PARM
FILEPARM
10
C
LIB
PARM
LIBPARM
10
*
* Delete the user space if it exists
*
C
CALL
'QUSDLTUS'
10
C
PARM
SPACENAME
C
PARM
IGNERR
*
* Create the user space
*
C
CALL
'QUSCRTUS'
C
PARM
SPACENAME
C
PARM
ATTRIBUTE
C
PARM
INIT_SIZE
C
PARM
' '
INIT_VALUE
1
C
PARM
AUTHORITY
C
PARM
TEXT
*
* Call the API to list the members in the requested file
*
C
CALL
'QUSLMBR'
C
PARM
SPACENAME
C
PARM
'MBRL0100'
MBR_LIST
8
C
PARM
FILE_LIB
C
PARM
WHICHMBR
C
PARM
OVERRIDE
*
* Get a pointer to the user-space
*
C
CALL
'QUSPTRUS'
C
PARM
SPACENAME
C
PARM
PTR
*
* Set the basing pointer for the member array
* MBRARR now overlays ARR starting at the beginning of
* the member information.
*
C
EVAL
MBRPTR = %ADDR(ARR(OFFSET))
C
MOVE
SIZE
CHARSIZE
3
C
EVAL
%SUBST(FIRST_LAST:1:3) = CHARSIZE
C
EVAL
%SUBST(FIRST_LAST:23:10) = MBRARR(1)
C
EVAL
%SUBST(FIRST_LAST:41:10) = MBRARR(SIZE)
C
FIRST_LAST
DSPLY
C
EVAL
*INLR = '1'
Figure 93 (Part 2 of 2). Example of using pointers and based structures with an API
When coding basing pointers, make sure that the pointer is set to storage that is
large enough and of the correct type for the based field. Figure 94 on page 196
shows some examples of how not to code basing pointers.
Chapter 10. Data Types and Data Formats
195
Procedure Pointer Data Type
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+...
8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
*
D chr10
S
10a
based(ptr1)
D char100
S
100a
based(ptr1)
D p1
S
5p 0 based(ptr1)
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
CL0N01++++++++++++++Opcode(E)+Extended Factor 2++++++++++++++++++++++++++++
*
*
* Set ptr1 to the address of p1, a numeric field
* Set chr10 (which is based on ptr1) to 'abc'
* The data written to p1 will be unreliable because of the data
* type incompatibility.
*
C
EVAL
ptr1 = %addr(p1)
C
EVAL
chr10 = 'abc'
*
* Set ptr1 to the address of chr10, a 10-byte field.
* Set chr100, a 100-byte field, all to 'x'
* 10 bytes are written to chr10, and 90 bytes are written in other
* storage, the location being unknown.
*
C
EVAL
ptr1 = %addr(chr10)
C
EVAL
chr100 = *all'x'
Figure 94. How Not to Code Basing Pointers
Procedure Pointer Data Type
Procedure pointers are used to point to procedures or functions. A procedure
pointer points to an entry point that is bound into the program. Procedure pointers
are defined on the definition specification.
The length of the procedure pointer field must be 16 bytes long and must be
aligned on a 16 byte boundary. This requirement for boundary alignment can cause
a pointer subfield of a data structure not to follow the preceding field directly, and
can cause multiple occurrence data structures to have non-contiguous occurrences.
For more information on the alignment of subfields, see “Aligning Data Structure
Subfields” on page 125.
The default initialization value for procedure pointers is *NULL.
Examples
196
ILE RPG for AS/400 Reference
Procedure Pointer Data Type
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
*
* Define a basing pointer field and initialize to the address of the
* data structure My_Struct.
*
D My_Struct
DS
D
My_array
10
DIM(50)
D
D Ptr1
S
16*
INZ(%ADDR(My_Struct))
*
* Or equivalently, defaults to length 16 if length not defined
*
D Ptr1
S
*
INZ(%ADDR(My_Struct))
*
* Define a procedure pointer field and initialize to NULL
*
D Ptr1
S
16*
PROCPTR INZ(*NULL)
*
* Define a procedure pointer field and initialize to the address
* of the procedure My_Proc.
*
D Ptr1
S
16*
PROCPTR INZ(%PADDR(My_Proc))
*
* Define pointers in a multiple occurrence data structure and map out
* the storage.
*
DDataS
DS
OCCURS(2)
D ptr1
*
D ptr2
*
D Switch
1A
*
* Storage map would be:
*
*
DataS
*
*
*
ptr1
*
*
ptr2
*
Switch
*
*
Pad
*
*
ptr1
*
*
ptr2
*
*
Switch
*
*
*
16 bytes
16 bytes
1 byte
15 bytes
16 bytes
16 bytes
1 byte
Figure 95. Defining pointers
Chapter 10. Data Types and Data Formats
197
Database Null Value Support
Database Null Value Support
In an ILE RPG program, you can select one of three different ways of handling
null-capable fields from an externally described database file. This depends on how
the ALWNULL keyword on a control specification is used (ALWNULL can also be
specified as a command parameter):
1. ALWNULL(*USRCTL) - read, write, update, and delete records with null values
and retrieve and position-to records with null keys.
2. ALWNULL(*INPUTONLY) - read records with null values to access the data in
the null fields
3. ALWNULL(*NO) - do not process records with null values
Note: For a program-described file, a null value in the record always causes a
data mapping error, regardless of the value specified on the ALWNULL
keyword.
User Controlled Support for Null-Capable Fields and Key Fields
When an externally described file contains null-capable fields and the
ALWNULL(*USRCTL) keyword is specified on a control specification, you can do
the following:
¹ Read, write, update, and delete records with null values from externally
described database files.
¹ Retrieve and position-to records with null keys using keyed operations, by
specifying an indicator in factor 2 of the KFLD associated with the field.
¹ Determine whether a null-capable field is actually null using the %NULLIND
built-in function on the right-hand-side of an expression.
¹ Set a null-capable field to be null for output or update using the %NULLIND
built-in function on the left-hand-side of an expression.
You are responsible for ensuring that fields containing null values are used correctly within the program. For example, if you use a null-capable field as factor 2 of
a MOVE operation, you should first check if it is null before you do the MOVE,
otherwise you may corrupt your result field value. You should also be careful when
outputting a null-capable field to a file that does not have the field defined as nullcapable, for example a WORKSTN or PRINTER file, or a program-described file.
Note: The value of the null indicator for a null-capable field is only considered for
these operations: input, output and file-positioning. Here are some examples
of operations where the the null indicator is not taken into consideration:
¹ DSPLY of a null-capable field shows the contents of the field even if the
null indicator is on.
¹ If you move a null-capable field to another null-capable field, and the
factor 2 field has the null indicator on, the the result field will get the
data from the factor 2 field. The corresponding null indicator for the
result field will not be set on.
¹ Comparison operations, including SORTA and LOOKUP, with null
capable fields do not consider the null indicators.
A field is considered null-capable if it is null-capable in any externally described
database record and is not defined as a constant in the program.
198
ILE RPG for AS/400 Reference
Database Null Value Support
Note: If the file used for an externally described data structure has null-capable
fields defined, the null attribute is not used in defining the RPG subfield.
When a field is considered null-capable in an RPG program, a null indicator is
associated with the field. Note the following:
¹ If the field is a multiple-occurrence data structure or a table, an array of null
indicators will be associated with the field. Each null indicator corresponds to
an occurrence of the data structure or element of the table.
¹ If the field is an array element, the entire array will be considered null-capable.
An array of null indicators will be associated with the array, each null indicator
corresponds to an array element.
¹ If the field is an element of an array subfield of a multiple-occurrence data
structure, an array of null indicators will be associated with the array for each
occurrence of the data structure.
Null indicators are initialized to zeros during program initialization and thus nullcapable fields do not contain null values when the program starts execution.
Input of Null-Capable Fields
For a field that is null-capable in the RPG program, the following will apply on input,
for DISK, SEQ, WORKSTN and SPECIAL files:
¹ When a null-capable field is read from an externally described file, the null indicator for the field is set on if the field is null in the record. Otherwise, the null
indicator is set off.
¹ If field indicators are specified and the null-capable field is null, all the field indicators will be set off.
¹ If a field is defined as null-capable in one file, and not null-capable in another,
then the field will be considered null-capable in the RPG program. However,
when you read the second file, the null indicator associated with the field will
always be set off.
¹ An input operation from a program-described file using a data structure in the
result field does not affect the null indicator associated with the data structure
or any of its subfields.
¹ Reading null-capable fields using input specifications for program-described
files always sets off the associated null indicators.
¹ If null-capable fields are not selected to be read due to a field-record-relation
indicator, the associated null indicator will not be changed.
Null-capable fields cannot be used as match fields or control-level fields.
Output of Null-Capable Fields
When a null-capable field is written (output or update) to an externally described
file, a null value is written out if the null indicator for the field is on at the time of the
operation.
When a null-capable field is output to or updated in an externally described database file, then if the field is null, the value placed in the buffer will be ignored by
data management.
Chapter 10. Data Types and Data Formats
199
Database Null Value Support
Note: Fields that have the null indicator on at the time of output have the data
moved to the buffer. This means that errors such as decimal-data error, or
basing pointer not set, will occur even if the null indicator for the field is on.
During an output operation to an externally described database file, if the file contains fields that are considered null-capable in the program but not null-capable in
the file, the null indicators associated with those null-capable fields will not be used.
Figure 96 shows how to read, write and update records with null values when the
ALWNULL(*USRCTL) option is used.
*..1....+....2....+....3....+....4....+....5....+....6....+....7....+....
*
*
* Specify the ALWNULL(*USRCTL) keyword on a control
* specification or compile the ILE RPG program with ALWNULL(*USRCTL)
* on the command.
*
HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*H ALWNULL(*USRCTL)
*
* DISKFILE contains a record REC which has 2 fields: FLD1 and FLD2
* Both FLD1 and FLD2 are null-capable.
*
FDISKFILE UF A E
DISK
*
* Read the first record.
* Update the record with new values for any fields which are not
* null.
C
READ
REC
10
C
IF
NOT %NULLIND(Fld1)
C
MOVE
'FLD1'
Fld1
C
ENDIF
C
IF
NOT %NULLIND(Fld2)
C
MOVE
'FLD2'
Fld2
C
ENDIF
C
UPDATE
REC
*
* Read another record.
* Update the record so that all fields are null.
* There is no need to set the values of the fields because they
* would be ignored.
C
READ
REC
10
C
EVAL
%NULLIND(Fld1) = *ON
C
EVAL
%NULLIND(Fld2) = *ON
C
UPDATE
REC
*
* Write a new record where Fld 1 is null and Fld 2 is not null.
*
C
EVAL
%NULLIND(Fld1) = *ON
C
EVAL
%NULLIND(Fld2) = *OFF
C
EVAL
Fld2 = 'New value'
C
WRITE
REC
Figure 96. Input and output of null-capable fields
200
ILE RPG for AS/400 Reference
Database Null Value Support
Keyed Operations
If you have a null-capable key field, you can search for records containing null
values by specifying an indicator in factor 2 of the KFLD operation and setting that
indicator on before the keyed input operation. If you do not want a null key to be
selected, you set the indicator off.
Figure 97 illustrates how keyed operations are used to position and retrieve
records with null keys.
*
* Assume File1 below contains a record Rec1 with a composite key
* made up of three key fields: Key1, Key2, and Key3. Key2 and Key3
* are null-capable. Key1 is not null-capable.
* Each key field is two characters long.
*
*..1....+....2....+....3....+....4....+....5....+....6....+....7....+..
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++
FFile1
IF
E
DISK
Figure 97 (Part 1 of 2). Example of keyed operations using null-capable key fields
Chapter 10. Data Types and Data Formats
201
Database Null Value Support
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.
C
Full_Kl
KLIST
C
KFLD
Key1
C
KFLD
*IN02
Key2
C
KFLD
*IN03
Key3
C
Partial_Kl
KLIST
C
KFLD
Key1
C
KFLD
*IN05
Key2
*
* *IN02 is ON and *IN03 is OFF for the SETLL operation below.
* File1 will be positioned at the next record that has a key
* that is equal to or greater than 'AA??CC' (where ?? is used
* in this example to indicate NULL)
*
* Because *IN02 is ON, the actual content in the search argument
* for Key2 will be ignored.
*
* If a record exists in File1 with 'AA' in Key1, a null Key2, and
* 'CC' in Key3, indicator 90 (the Eq indicator) will be set ON.
*
C
MOVE
'AA'
Key1
C
MOVE
'CC'
Key3
C
EVAL
*IN02 = '1'
C
EVAL
*IN03 = '0'
C
Full_Kl
SETLL
Rec1
90
*
* The CHAIN operation below will retrieve a record with 'JJ' in Key1,
* 'KK' in Key2, and a null Key3. Again, because *IN03 is ON, even
* if the programmer had moved some value (say 'XX') into the search
* argument for Key3, 'XX' will not be used. This means if File1
* actually has a record with a key 'JJKKXX', that record will not
* be retrieved.
*
C
MOVE
'JJ'
Key1
C
MOVE
'KK'
Key2
C
EVAL
*IN02 = '0'
C
EVAL
*IN03 = '1'
C
Full_Kl
CHAIN
Rec1
80
*
* The CHAIN operation below uses a partial key as the search argument.
* It will retrieve a record with 'NN' in Key1, a null key2, and any
* value including a null value in Key3.
*
* In the database, the NULL value occupies the highest position in
* the collating sequence. Assume the keys in File1 are in ascending
* sequence. If File1 has a record with 'NN??xx' as key (where ??
* means NULL and xx means any value other than NULL), that record
* will be retrieved. If such a record does not exist in File1, but
* File1 has a record with 'NN????' as key, the 'NN????' record will
* be retrieved. The null flags for Key2 and Key3 will be set ON
* as a result.
*
C
MOVE
'NN'
Key1
C
SETON
05
C
Partial_Kl
CHAIN
Rec1
70
Figure 97 (Part 2 of 2). Example of keyed operations using null-capable key fields
202
ILE RPG for AS/400 Reference
Error Handling for Database Data Mapping Errors
Input-Only Support for Null-Capable Fields
When an externally described input-only file contains null-capable fields and the
ALWNULL(*INPUTONLY) keyword is specified on a control specification, the following conditions apply:
¹ When a record is retrieved from a database file and there are some fields containing null values in the record, database default values for the null-capable
fields will be placed into those fields containing null values. The default value
will be the user defined DDS defaults or system defaults.
¹ You will not be able to determine whether any given field in the record has a
null value.
¹ Control-level indicators, match-field entries and field indicators are not allowed
on an input specification if the input field is a null-capable field from an
externally described input-only file.
¹ Keyed operations are not allowed when factor 1 of a keyed input calculation
operation corresponds to a null-capable key field in an externally described
input-only file.
Note: The same conditions apply for *INPUTONLY or *YES when specified on the
ALWNULL command parameter.
ALWNULL(*NO)
When an externally described file contains null-capable fields and the
ALWNULL(*NO) keyword is specified on a control specification, the following conditions apply:
¹ A record containing null values retrieved from a file will cause a data mapping
error and an error message will be issued.
¹ Data in the record is not accessible and none of the fields in the record can be
updated with the values from the input record containing null values.
¹ With this option, you cannot place null values in null-capable fields for updating
or adding a record. If you want to place null values in null-capable fields, use
the ALWNULL(*USRCTL) option.
Error Handling for Database Data Mapping Errors
For any input or output operation, a data mapping error will cause a severe error
message to be issued. For blocked output, if one or more of the records in the
block contains data mapping errors and the file is closed before reaching the end of
the block, a severe error message is issued and a system dump is created.
Chapter 10. Data Types and Data Formats
203
Error Handling for Database Data Mapping Errors
204
ILE RPG for AS/400 Reference
Chapter 11. Editing Numeric Fields
Editing provides a means of:
¹ Punctuating numeric fields, including the printing of currency symbols, commas,
periods, minus sign, and floating minus
¹ Moving a field sign from the rightmost digit to the end of the field
¹ Blanking zero fields
¹ Managing spacing in arrays
¹ Editing numeric values containing dates
¹ Floating a currency symbol
¹ Filling a print field with asterisks
This chapter applies only to non-float numeric fields. To output float fields in the
external display representation, specify blank in position 52 of the output specification. To obtain the external display representation of a float value in calculations,
use the %EDITFLT built-in function.
A field can be edited by edit codes, or edit words. You can print fields in edited
format using output specifications or you can obtain the edited value of the field in
calulation specifications using the built-in functions %EDITC (edit code) and
%EDITW (edit word).
When you print fields that are not edited, the fields are printed as follows:
¹ Float fields are printed in the external display representation.
¹ Other numeric fields are printed in zoned numeric representation.
The following examples show why you may want to edit numeric output fields.
Type of Field
Field in the Computer
Printing of Unedited Field
Printing of Edited
Field
Alphanumeric
JOHN T SMITH
JOHN T SMITH
JOHN T SMITH
Numeric
(positive)
0047652
0047652
47652
Numeric
(negative)
004765K
004765K
47652-
The unedited alphanumeric field and the unedited positive numeric field are easy to
read when printed, but the unedited negative numeric field is confusing because it
contains a K, which is not numeric. The K is a combination of the digit 2 and the
negative sign for the field. They are combined so that one of the positions of the
field does not have to be set aside for the sign. The combination is convenient for
storing the field in the computer, but it makes the output hard to read. Therefore, to
improve the readability of the printed output, numeric fields should be edited before
they are printed.
 Copyright IBM Corp. 1994, 1999
205
Edit Codes
Edit Codes
Edit codes provide a means of editing numeric fields according to a predefined
pattern. They are divided into three categories: simple (X, Y, Z), combination (1
through 4, A through D, J through Q), and user-defined (5 through 9). In output
specifications, you enter the edit code in position 44 of the field to be edited. In
calculation specifications, you specify the edit code as the second parameter of the
%EDITC built-in function.
Simple Edit Codes
You can use simple edit codes to edit numeric fields without having to specify any
punctuation. These codes and their functions are:
¹ The X edit code ensures a hexadecimal F sign for positive fields. However,
because the system does this, you normally do not have to specify this code.
Leading zeros are not suppressed. The X edit code does not modify negative
numbers.
¹ The Y edit code is normally used to edit a 3- to 9-digit date field. It suppresses
the leftmost zeros of date fields, up to but not including the digit preceding the
first separator. Slashes are inserted to separate the day, month, and year. The
“DATEDIT(fmt{separator})” on page 238 and “DECEDIT(*JOBRUN | 'value')” on
page 238 keywords on the control specification can be used to alter edit
formats.
Note: The Y edit code is not valid for *YEAR, *MONTH, and *DAY.
¹ The Z edit code removes the sign (plus or minus) from and suppresses the
leading zeros of a numeric field. The decimal point is not placed in the field.
Combination Edit Codes
The combination edit codes (1 through 4, A through D, J through Q) punctuate a
numeric field.
The DECEDIT keyword on the control specification determines what character is
used for the decimal separator and whether leading zeros are suppressed. The
decimal position of the source field determines whether and where a decimal point
is placed. If decimal positions are specified for the source field and the zero
balance is to be suppressed, the decimal separator is included only if the field is
not zero. If a zero balance is to be suppressed, a zero field is output as blanks.
When a zero balance is not to be suppressed and the field is equal to zero, either
of the following is output:
¹ A decimal separator followed by n zeros, where n is the number of decimal
places in the field
¹ A zero in the units position of a field if no decimal places are specified.
You can use a floating currency symbol or asterisk protection with any of the 12
combination edit codes. The floating currency symbol appears to the left of the first
significant digit. The floating currency symbol does not print on a zero balance
when an edit code is used that suppresses the zero balance. The currency symbol
does not appear on a zero balance when an edit code is used that suppresses the
zero balance.
206
ILE RPG for AS/400 Reference
Edit Codes
The currency symbol for the program is a dollar sign ($) unless a currency symbol
is specified with the CURSYM keyword on the control specification.
To specify a floating currency symbol in output specifications, code the currency
symbol in positions 53-55 as well as an edit code in position 44 for the field to be
edited.
For built-in function %EDITC, you specify a floating currency symbol in the third
parameter. To use the currency symbol for the program, specify *CURSYM. To
use another currency symbol, specify a character constant of length 1.
Asterisk protection causes an asterisk to replace each zero suppressed. A complete field of asterisks replaces the fiield on a zero balance source field. To specify
asterisk protection in output specifications, code an asterisk constant in positions 53
through 55 of the output specifications, along with an edit code. To specify asterisk
protection using the built-in function %EDITC, specify *ASTFILL as the third parameter.
Asterisk fill and the floating currency symbol cannot be used with the simple (X, Y,
Z) or with the user-defined (5 through 9) edit codes.
A currency symbol can appear before the asterisk fill (fixed currency symbol). You
can do this in output specifications with the following coding:
1. Place a currency symbol constant in position 53 of the first output specification.
The end position specified in positions 47-51 should be one space before the
beginning of the edited field.
2. In the second output specification, place the edit field in positions 30-43, an edit
code in position 44, end position of the edit field in positions 47-51, and '*' in
positions 53-55.
You can do this using the %EDITC built-in function by concatenating the currency
symbol to the %EDITC result.
C
EVAL
X = '$' + %EDITC(N: 'A' : *ASTFILL)
In output specifications, when an edit code is used to print an entire array, two
blanks precede each element of the array (except the first element).
Note: You cannot edit an array using the %EDITC built-in function.
Table 18 summarizes the functions of the combination edit codes. The codes edit
the field in the format listed on the left. A negative field can be punctuated with no
sign, CR, a minus sign (-), or a floating minus sign as shown on the top of the
figure.
Table 18 (Page 1 of 2). Combination Edit Codes
Negative Balance Indicator
Prints
with
Grouping
Separator
Prints
Zero
Balance
Yes
Yes
Yes
No
No Sign
CR
-
Floating
Minus
1
A
J
N
2
B
K
0
Chapter 11. Editing Numeric Fields
207
Edit Codes
Table 18 (Page 2 of 2). Combination Edit Codes
Negative Balance Indicator
Prints
with
Grouping
Separator
Prints
Zero
Balance
No
Yes
No
No
No Sign
CR
-
Floating
Minus
3
C
L
P
4
D
M
Q
User-Defined Edit Codes
IBM has predefined edit codes 5 through 9. You can use them as they are, or you
can delete them and create your own. For a description of the IBM-supplied edit
codes, see the chapter on “Edit Descriptions” in the Programming Reference
Summary, SX41-5720-03.
The user-defined edit codes allow you to handle common editing problems that
would otherwise require the use of an edit word. Instead of the repetitive coding of
the same edit word, a user-defined edit code can be used. These codes are
system defined by the CL command CRTEDTD (Create Edit Description).
When you edit a field defined to have decimal places, be sure to use an edit word
that has an editing mask for both the fractional and integer portions of the field.
Remember that when a user-defined edit code is specified in a program, any
system changes made to that user-defined edit code are not reflected until the
program is recompiled. For further information on CRTEDTD, see the CL Reference
(Abridged).
Editing Considerations
Remember the following when you specify any of the edit codes:
¹ Edit fields of a non-printer file with caution. If you do edit fields of a non-printer
file, be aware of the contents of the edited fields and the effects of any operations you do on them. For example, if you use the file as input, the fields
written out with editing must be considered character fields, not numeric fields.
¹ Consideration should be given to data added by the edit operation. The amount
of punctuation added increases the overall length of the edited value. If these
added characters are not considered when editing in output specifications, the
output fields may overlap.
¹ The end position specified for output is the end position of the edited field. For
example, if any of the edit codes J through M are specified, the end position is
the position of the minus sign (or blank if the field is positive).
¹ The compiler assigns a character position for the sign even for unsigned
numeric fields.
208
ILE RPG for AS/400 Reference
Edit Codes
Summary of Edit Codes
Table 19 summarizes the edit codes and the options they provide. A simplified
version of this table is printed above positions 45 through 70 on the output specifications. Table 20 on page 211 shows how fields look after they are edited.
Table 21 on page 212 shows the effect that the different edit codes have on the
same field with a specified end position for output.
Table 19 (Page 1 of 2). Edit Codes
DECEDIT Keyword Parameter
Edit
Code
Commas
Decimal
Point
Sign for
Negative
Balance
'.'
','
'0,'
'0.'
Zero
Suppress
1
Yes
Yes
No Sign
.00 or 0
,00 or 0
0,00 or 0
0.00 or 0
Yes
2
Yes
Yes
No Sign
Blanks
Blanks
Blanks
Blanks
Yes
3
Yes
No Sign
.00 or 0
,00 or 0
0,00 or 0
0.00 or 0
Yes
4
Yes
No Sign
Blanks
Blanks
Blanks
Blanks
Yes
5-91
A
Yes
Yes
CR
.00 or 0
,00 or 0
0,00 or 0
0.00 or 0
Yes
B
Yes
Yes
CR
Blanks
Blanks
Blanks
Blanks
Yes
C
Yes
CR
.00 or 0
,00 or 0
0,00 or 0
0.00 or 0
Yes
D
Yes
CR
Blanks
Blanks
Blanks
Blanks
Yes
J
Yes
Yes
- (minus)
.00 or 0
,00 or 0
0,00 or 0
0.00 or 0
Yes
K
Yes
Yes
- (minus)
Blanks
Blanks
Blanks
Blanks
Yes
L
Yes
- (minus)
.00 or 0
,00 or 0
0,00 or 0
0.00 or 0
Yes
M
Yes
- (minus)
Blanks
Blanks
Blanks
Blanks
Yes
N
Yes
Yes
- (floating
minus)
.00 or 0
,00 or 0
0,00 or 0
0.00 or 0
Yes
O
Yes
Yes
- (floating
minus)
Blanks
Blanks
Blanks
Blanks
Yes
P
Yes
- (floating
minus)
.00 or 0
,00 or 0
0,00 or 0
0.00 or 0
Yes
Q
Yes
- (floating
minus)
Blanks
Blanks
Blanks
Blanks
Yes
X2
Y3
Yes
Z4
Yes
Chapter 11. Editing Numeric Fields
209
Edit Codes
Table 19 (Page 2 of 2). Edit Codes
DECEDIT Keyword Parameter
Edit
Code
Commas
Decimal
Point
Sign for
Negative
Balance
'.'
','
'0,'
'0.'
Zero
Suppress
Notes:
1. These are the user-defined edit codes.
2. The X edit code ensures a hexadecimal F sign for positive values. Because the system does this for you,
normally you do not have to specify this code.
3. The Y edit code suppresses the leftmost zeros of date fields, up to but not including the digit preceding the
first separator. The Y edit code also inserts slashes (/) between the month, day, and year according to the
following pattern:
nn/n
nn/nn
nn/nn/n
nn/nn/nn
nnn/nn/nn
nn/nn/nnnn
nnn/nn/nnnn
nnnn/nn/nn
nnnnn/nn/nn
4. The Z edit code removes the sign (plus or minus) from a numeric field and suppresses leading zeros.
210
ILE RPG for AS/400 Reference
Edit Codes
Table 20. Examples of Edit Code Usage
Edit
Codes
Positive
NumberTwo
Decimal
Positions
Positive
NumberNo
Decimal
Positions
Negative
NumberThree
Decimal
Positions
Negative
NumberNo
Decimal
Positions
Zero
BalanceTwo
Decimal
Positions
Zero
BalanceNo
Decimal
Positions
Unedited
1234567
1234567
00012Ï5
00012Ï5
000000
000000
1
12,345.67
1,234,567
.120
120
.00
0
2
12,345.67
1,234,567
.120
120
3
12345.67
1234567
.120
120
.00
0
4
12345.67
1234567
.120
120
A
12,345.67
1,234,567
.120CR
120CR
.00
0
B
12.345.67
1,234,567
.120CR
120CR
C
12345.67
1234567
.120CR
120CR
.00
0
D
12345.67
1234567
.120CR
120CR
J
12,345.67
1,234,567
.120-
120-
.00
0
K
12,345,67
1,234,567
.120-
120-
L
12345.67
1234567
.120-
120-
.00
0
M
12345.67
1234567
.120-
120-
N
12,345.67
1,234,567
-.120
-120
.00
0
O
12,345,67
1,234,567
-.120
-120
P
12345.67
1234567
-.120
-120
.00
0
Q
12345.67
1234567
-.120
-120
1234567
00012Ï5
00012Ï5
000000
000000
0/01/20
0/01/20
0/00/00
0/00/00
120
120
5-91
X2
1234567
Y3
Z4
1234567
1234567
Notes:
1. These edit codes are user-defined.
2. The X edit code ensures a hex F sign for positive values. Because the system does this for you, normally you
do not have to specify this code.
3. The Y edit code suppresses the leftmost zeros of date fields, up to but not including the digit preceding the
first separator. The Y edit code also inserts slashes (/) between the month, day, and year according to the
following pattern:
nn/n
nn/nn
nn/nn/n
nn/nn/nn
nnn/nn/nn
nn/nn/nnnn
nnn/nn/nnnn
nnnn/nn/nn
nnnnn/nn/nn
Format
Format
Format
Format
used
used
used
used
with
with
with
with
M, D
M, D
Y in
Y in
or blank
or blank
position
position
in position 19
in position 19
19
19
4. The Z edit code removes the sign (plus or minus) from a numeric field and suppresses leading zeros of a
numeric field.
5. The Ï represents a blank. This may occur if a negative zero does not correspond to a printable character.
Chapter 11. Editing Numeric Fields
211
Edit Words
Table 21. Effects of Edit Codes on End Position
Negative Number, 2 Decimal Positions. End Position
Specified as 10.
Output Print Positions
Edit Code
3
4
5
6
7
8
9
10
0
0
4
1
K1
1
4
.
1
2
2
4
.
1
2
3
4
.
1
2
4
4
.
1
2
Unedited
11
5-92
A
4
.
1
2
C
R
B
4
.
1
2
C
R
C
4
.
1
2
C
R
D
4
.
1
2
C
R
J
4
.
1
2
-
K
4
.
1
2
-
L
4
.
1
2
-
M
4
.
1
2
-
N
-
4
.
1
2
O
-
4
.
1
2
P
-
4
.
1
2
Q
-
4
.
1
2
X
0
0
4
1
K1
/
4
1
/
2
4
1
2
Y
0
Z
Notes:
1. K represents a negative 2.
2. These are user-defined edit codes.
Edit Words
If you have editing requirements that cannot be met by using the edit codes
described above, you can use an edit word. An edit word is a character literal or a
named constant specified in positions 53 - 80 of the output specification. It
describes the editing pattern for an numeric and allows you to directly specify:
¹ Blank spaces
¹ Commas and decimal points, and their position
¹ Suppression of unwanted zeros
¹ Leading asterisks
¹ The currency symbol, and its position
212
ILE RPG for AS/400 Reference
Edit Words
¹ Addition of constant characters
¹ Output of the negative sign, or CR, as a negative indicator.
The edit word is used as a template, which the system applies to the source data
to produce the output.
The edit word may be specified directly on an output specification or may be specified as a named constant with a named constant name appearing in the edit word
field of the output specification. You can obtain the edited value of the field in
calulation specifications using the built-in function %EDITW (edit word).
Named constants, used as edit words, are limited to 115 characters.
How to Code an Edit Word
To output using an edit word, code the output specifications as shown below:
Position
Entry
21-29
Can contain conditioning indicators.
30-43
Contains the name of the numeric field from which the data that is to be
edited is taken.
44
Edit code. Must be blank, if you are using an edit word to edit the
source data.
45
A “B” in this position indicates that the source data is to be set to zero
or blanks after it has been edited and output. Otherwise the source data
remains unchanged.
47-51
Identifies the end (rightmost) position of the field in the output record.
53-80
Edit word. Can be up to 26 characters long and must be enclosed by
apostrophes, unless it is a named constant. Enter the leading apostrophe, or begin the named constant name in column 53. The edit word,
unless a named constant, must begin in column 54.
To edit using an edit word in calculation specifications, use built-in function
%EDITW, specifying the value to be edited as the first parameter, and the edit word
as the second parameter.
Parts of an Edit Word
An edit word consists of three parts: the body, the status, and the expansion. The
following shows the three parts of an edit word:
E D I T
b
b
b
,
b
b
0.
Body
.
W O R D
b
b
&
C
R
Status
&
&
T
O
T
Expansion
Figure 98. Parts of an Edit Word
The body is the space for the digits transferred from the source data field to the
edited result. The body begins at the leftmost position of the edit word. The number
of blanks (plus one zero or an asterisk) in the edit word body must be equal to or
Chapter 11. Editing Numeric Fields
213
Edit Words
greater than the number of digits of the source data field to be edited. The body
ends with the rightmost character that can be replaced by a digit.
The status defines a space to allow for a negative indicator, either the two letters
CR or a minus sign (-). The negative indicator specified is output only if the source
data is negative. All characters in the edit word between the last replaceable character (blank, zero suppression character) and the negative indicator are also output
with the negative indicator only if the source data is negative; if the source data is
positive, these status positions are replaced by blanks. Edit words without the CR
or - indicators have no status positions.
The status must be entered after the last blank in the edit word. If more than one
CR follows the last blank, only the first CR is treated as a status; the remaining
CRs are treated as constants. For the minus sign to be considered as a status, it
must be the last character in the edit word.
The expansion is a series of ampersands and constant characters entered after the
status. Ampersands are replaced by blank spaces in the output; constants are
output as is. If status is not specified, the expansion follows the body.
Forming the Body of an Edit Word
The following characters have special meanings when used in the body of an edit
word:
Blank: Blank is replaced with the character from the corresponding position of the
value to be edited. A blank position is referred to as a digit position.
Decimals and Commas: Decimals and commas are in the same relative position
in the edited output field as they are in the edit word unless they appear to the left
of the first significant digit in the edit word. In that case, they are blanked out or
replaced by an asterisk.
In the following examples below, all the leading zeros will be suppressed (default)
and the decimal point will not appear unless there is a significant digit to its left.
Edit Word
Source Data
Appears in Edited Result as:
'ÏÏÏÏÏÏÏ'
0000072
ÏÏÏÏÏ72
'ÏÏÏÏÏÏÏ.ÏÏ'
000000012
ÏÏÏÏÏÏÏÏ12
'ÏÏÏÏÏÏÏ.ÏÏ'
000000123
ÏÏÏÏÏÏ1.23
Zeros: The first zero in the body of the edit word is interpreted as an end-zerosuppression character. This zero is placed where zero suppression is to end. Subsequent zeros put into the edit word are treated as constants (see “Constants”
below).
Any leading zeros in the source data are suppressed up to and including the position of the end-zero-suppression character. Significant digits that would appear in
the end-zero-suppression character position, or to the left of it, are output.
Edit Word
Source Data
Appears in Edited Result as:
'ÏÏÏ0ÏÏÏÏÏÏ'
00000004
ÏÏÏÏ000004
214
ILE RPG for AS/400 Reference
Edit Words
Edit Word
Source Data
Appears in Edited Result as:
'ÏÏÏ0ÏÏÏÏÏÏ'
012345
ÏÏÏÏ012345
'ÏÏÏ0ÏÏÏÏÏÏ'
012345678
ÏÏ12345678
If the leading zeros include, or extend to the right of, the end-zero-suppression
character position, that position is replaced with a blank. This means that if you
wish the same number of leading zeros to appear in the output as exist in the
source data, the edit word body must be wider than the source data.
Edit Word
Source Data
Appears in Edited Result as:
'0ÏÏÏ'
0156
Ï156
'0ÏÏÏÏ'
0156
Ï0156
Constants (including commas and decimal point) that are placed to the right of the
end-zero-suppression character are output, even if there is no source data. Constants to the left of the end-zero-suppression character are only output if the source
data has significant digits that would be placed to the left of these constants.
Edit Word
Source Data
Appears in Edited Result as:
'ÏÏÏÏÏÏ0.ÏÏ'
000000001
ÏÏÏÏÏÏÏ.01
'ÏÏÏÏÏÏ0.ÏÏ'
000000000
ÏÏÏÏÏÏÏ.00
'ÏÏÏ,Ï0Ï.ÏÏ'
00000012
ÏÏÏÏÏÏ0.12
'ÏÏÏ,Ï0Ï.ÏÏ'
00000123
ÏÏÏÏÏÏ1.23
'Ï0Ï,ÏÏÏ.ÏÏ'
00000123
ÏÏ0,001.23
Asterisk: The first asterisk in the body of an edit word also ends zero suppression. Subsequent asterisks put into the edit word are treated as constants (see
“Constants” below). Any zeros in the edit word following this asterisk are also
treated as constants. There can be only one end-zero-suppression character in an
edit word, and that character is the first asterisk or the first zero in the edit word.
If an asterisk is used as an end-zero-suppression character, all leading zeros that
are suppressed are replaced with asterisks in the output. Otherwise, the asterisk
suppresses leading zeros in the same way as described above for “Zeros”.
Edit Word
Source Data
Appears in Edited Result as:
'*ÏÏÏÏÏÏ.ÏÏ'
000000123
*ÏÏÏÏÏ1.23
'ÏÏÏÏÏ*Ï.ÏÏ'
000000000
******0.00
'ÏÏÏÏÏ*Ï.ÏÏ**'
000056342
****563.42**
Note that leading zeros appearing after the asterisk position are output as leading
zeros. Only the suppressed leading zeros, including the one in the asterisk position,
are replaced by asterisks.
Currency Symbol: A currency symbol followed directly by a first zero in the edit
word (end-zero-suppression character) is said to float. All leading zeros are suppressed in the output and the currency symbol appears in the output immediately to
the left of the most significant digit.
Chapter 11. Editing Numeric Fields
215
Edit Words
Edit Word
Source Data
Appears in Edited Result as:
'ÏÏ,ÏÏÏ,Ï$0.ÏÏ'
000000012
ÏÏÏÏÏÏÏÏÏ$.12
'ÏÏ,ÏÏÏ,Ï$0.ÏÏ'
000123456
ÏÏÏÏ$1,234.56
If the currency symbol is put into the first position of the edit word, then it will
always appear in that position in the output. This is called a fixed currency symbol.
Edit Word
Source Data
Appears in Edited Result as:
'$Ï,ÏÏÏ,ÏÏ0.ÏÏ'
000123456
$ÏÏÏÏ1,234.56
'$ÏÏ,ÏÏÏ,0Ï0.ÏÏ'
000000000
$ÏÏÏÏÏÏÏÏ00.00
'$Ï,ÏÏÏ,*ÏÏ.ÏÏ'
000123456
$****1,234.56
A currency symbol anywhere else in the edit word and not immediately followed by
a zero end-suppression-character is treated as a constant (see “Constants” below).
Ampersand: Causes a blank in the edited field. The example below might be
used to edit a telephone number. Note that the zero in the first position is required
to print the constant AREA.
Edit Word
Source Data
Appears in Edited Result as:
'0AREA&ÏÏÏ&NO.&ÏÏÏ-ÏÏÏÏ'
4165551212
ÏAREAÏ416ÏNO.Ï555-1212
Constants: All other characters entered into the body of the edit word are treated
as constants. If the source data is such that the output places significant digits or
leading zeros to the left of any constant, then that constant appears in the output.
Otherwise, the constant is suppressed in the output. Commas and the decimal
point follow the same rules as for constants. Notice in the examples below, that the
presence of the end-zero-suppression character as well as the number of significant digits in the source data, influence the output of constants.
The following edit words could be used to print cheques. Note that the second
asterisk is treated as a constant, and that, in the third example, the constants preceding the first significant digit are not output.
Edit Word
Source Data
Appears in Edited Result as:
'$ÏÏÏÏÏÏ**DOLLARS&ÏÏ&CTS'
000012345
$****123*DOLLARSÏ45ÏCTS
'$ÏÏÏÏÏÏ**DOLLARS&ÏÏ&CTS'
000000006
$********DOLLARSÏ06ÏCTS
'$ÏÏÏÏÏÏÏ&DOLLARS&ÏÏ&CTS'
000000006
$ÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏÏ6ÏCTS
A date could be edited by using either edit word:
Edit Word
Source Data
Appears in Edited Result as:
'ÏÏ/ÏÏ/ÏÏ'
010388
Ï1/03/88
'0ÏÏ/ÏÏ/ÏÏ'
010389
Ï01/03/89
Note that any zeros or asterisks following the first occurrence of an edit word are
treated as constants. The same is true for - and CR:
216
ILE RPG for AS/400 Reference
Edit Words
Edit Word
Source Data
Appears in Edited Result as:
'ÏÏ0.ÏÏ000'
01234
Ï12.34000
'ÏÏ*.ÏÏ000'
01234
*12.34000
Forming the Status of an Edit Word
The following characters have special meanings when used in the status of an edit
word:
Ampersand: Causes a blank in the edited output field. An ampersand cannot be
placed in the edited output field.
CR or minus symbol: If the sign in the edited output is plus (+), these positions
are blanked out. If the sign in the edited output field is minus (−), these positions
remain undisturbed.
The following example adds a negative value indication. The minus sign will print
only when the value in the field is negative. A CR symbol fills the same function as
a minus sign.
Edit Word
Source Data
Appears in Edited Result as:
'ÏÏÏÏÏÏÏ.ÏÏ-'
000000123-
ÏÏÏÏÏÏ1.23-
'ÏÏÏÏÏÏÏ.ÏÏ-'
000000123
ÏÏÏÏÏÏ1.23Ï
Constants between the last replaceable character and the - or CR symbol will print
only if the field is negative; otherwise, blanks will appear in these positions. Note
the use of ampersands to represent blanks:
Edit Word
Source Data
Appears in Edited Result as:
'Ï,ÏÏÏ,ÏÏ0.ÏÏ&30&DAY&CR'
000000123-
ÏÏÏÏÏÏÏÏÏ1.23Ï30ÏDAYÏCR
'Ï,ÏÏÏ,ÏÏ0.ÏÏ&30&DAY&CR'
000000123
ÏÏÏÏÏÏÏÏÏ1.23ÏÏÏÏÏÏÏÏÏÏ
Formatting the Expansion of an Edit Word
The characters in the expansion portion of an edit word are always used. The
expansion cannot contain blanks. If a blank is required in the edited result, specify
an ampersand in the body of the edit word.
Constants may be added to appear with any value of the number:
Edit Word
Source Data
Appears in Edited Result as:
'Ï,ÏÏ0.ÏÏ&CR&NET'
000123-
ÏÏÏÏ1.23ÏCRÏNET
'Ï,ÏÏ0.ÏÏ&CR&NET'
000123
ÏÏÏÏ1.23ÏÏÏÏNET
Note that the CR in the middle of a word may be detected as a negative field value
indication. If a word such as SECRET is required, use the coding in the example
below.
Chapter 11. Editing Numeric Fields
217
Editing Externally Described Files
Edit Word
Source Data
Appears in Edited Result as:
'ÏÏ0.ÏÏ&SECRET'
12345-
123.45ÏSECRET
'ÏÏ0.ÏÏ&SECRET'
12345
123.45ÏÏÏÏÏET
'ÏÏ0.ÏÏ&CR&&SECRET'
12345
123.45ÏÏÏÏÏSECRET
Summary of Coding Rules for Edit Words
The following rules apply to edit words in output specifications:
¹ Position 44 (edit codes) must be blank.
¹ Positions 30 through 43 (field name) must contain the name of a numeric field.
¹ An edit word must be enclosed in apostrophes, unless it is a named constant.
Enter the leading apostrophe or begin a named constant name in position 53.
The edit word itself must begin in position 54.
The following rules apply to edit words in general:
¹ The edit word can contain more digit positions (blanks plus the initial zero or
asterisk) than the field to be edited, but must not contain less. If there are more
digit positions in the edit word than there are digits in the field to be edited,
leading zeros are added to the field before editing.
¹ If leading zeros from the source data are desired, the edit word must contain
one more position than the field to be edited, and a zero must be placed in the
high-order position of the edit word.
¹ In the body of the edit word only blanks and the zero-suppression stop characters (zero and asterisk) are counted as digit positions. The floating currency
symbol is not counted as a digit position.
¹ When the floating currency symbol is used, the sum of the number of blanks
and the zero-suppression stop character (digit positions) contained in the edit
word must be equal to or greater than the number of positions in the field to be
edited.
¹ Any zeros or asterisks following the leftmost zero or asterisk are treated as
constants; they are not replaceable characters.
¹ When editing an unsigned integer field, DB and CR are allowed and will always
print as blanks.
Editing Externally Described Files
To edit output for externally described files, place the edit codes in data description
specifications (DDS), instead of in RPG IV specifications. See the DDS Reference
for information on how to specify edit codes in the data description specifications.
However, if an externally described file, which has an edit code specified, is to be
written out as a program described output file, you must specify editing in the
output specifications. In this case, any edit codes in the data description specifications are ignored.
218
ILE RPG for AS/400 Reference
Specifications
This section describes the RPG IV specifications. First, information common to
several specifications, such as keyword syntax and continuation rules is described.
Next, the specifications are described in the order in which they must be entered in
your program. Each specification description lists all the fields on the specification
and explains all the possible entries.
 Copyright IBM Corp. 1994, 1999
219
220
ILE RPG for AS/400 Reference
RPG IV Specification Types
Chapter 12. About Specifications
RPG IV source is coded on a variety of specifications. Each specification has a
specific set of functions.
This reference contains a detailed description of the individual RPG IV specifications. Each field and its possible entries are described. Chapter 22, “Operation
Codes” on page 427 describes the operation codes that are coded on the calculation specification, which is described in Chapter 17, “Calculation Specifications”
on page 325.
RPG IV Specification Types
There are three groups of source records that may be coded in an RPG IV
program: the main source section, the subprocedure section, and the program data
section. The main source section consists of the first set of H, F, D, I, C, and O
specifications in a module. If the keyword NOMAIN is not specified, it corresponds
to a standalone program or a main procedure. If NOMAIN is specified, it does not
contain a main procedure, and so it does not contain any executable calculations.
Every module requires a main source section independently of whether subprocedures are coded.
The subprocedure section contains specifications that define any subprocedures
coded within a module. The program data section contains source records with
data that is supplied at compile time.
The following illustration shows the types of source records that may be entered
into each group and their order.
Note
The RPG IV source must be entered into the system in the order shown. Any of
the specification types can be absent, but at least one from the main source
section must be present.
 Copyright IBM Corp. 1994, 1999
221
RPG IV Specification Types
Compile-Time Array and Table Data
Alternate Collating Sequence Records
File Translation records
Program Data
P
Procedure
Calculation
D
P
Definition
Procedure
Subprocedure
Output
Calculation
Input
D
Definition
File Description
Control
Main Source Section
Figure 99. Source Records and Their Order in an RPG IV Source Program
Main Source Section Specifications
222
.H/
Control (Header) specifications provide information about program generation and running of the compiled program. Refer to Chapter 13,
“Control Specifications” on page 231 for a description of the entries on
this specification.
.F/
File description specifications define all files in the program. Refer to
Chapter 14, “File Description Specifications” on page 249 for a
description of the entries on this specification.
.D/
Definition specifications define items used in your program. Arrays,
tables, data structures, subfields, constants, standalone fields, and prototypes and their parameters are defined on this specification. Refer to
Chapter 15, “Definition Specifications” on page 273 for a description of
the entries on this specification.
.I/
Input specifications describe records, and fields in the input files and
indicate how the records and fields are used by the program. Refer to
Chapter 16, “Input Specifications” on page 309 for a description of the
entries on this specification.
ILE RPG for AS/400 Reference
RPG IV Specification Types
.C/
Calculation specifications describe calculations to be done by the
program and indicate the order in which they are done. Calculation
specifications can control certain input and output operations. Refer to
Chapter 17, “Calculation Specifications” on page 325 for a description
of the entries on this specification.
.O/
Output specifications describe the records and fields and indicate when
they are to be written by the program. Refer to Chapter 18, “Output
Specifications” on page 335 for a description of the entries on this specification.
Subprocedure Specifications
.P/
Procedure specifications describe the procedure-interface definition of a
prototyped program or procedure. Refer to Chapter 19, “Procedure
Specifications” on page 351 for a description of the entries on this specification.
.D/
Definition specifications define items used in the prototyped procedure.
Procedure-interface definitions, entry parameters, and other local items
are defined on this specification. Refer to Chapter 15, “Definition
Specifications” on page 273 for a description of the entries on this specification.
.C/
Calculation specifications perform the logic of the prototyped procedure.
Refer to Chapter 17, “Calculation Specifications” on page 325 for a
description of the entries on this specification.
The RPG IV language consists of a mixture of position-dependent code and free
form code. Those specifications which support keywords (control, file description,
definition, and procedure) allow free format in the keyword fields. The calculation
specification allows free format with those operation codes which support an
extended-factor 2. Otherwise, RPG IV entries are position specific. To represent
this, each illustration of RPG IV code will be in listing format with a scale drawn
across the top.
Program Data
Source records with program data follow all source specifications. The first line of
the data section must start with **.
If desired, you can indicate the type of program data that follows the **, by specifying any of these keywords as required: “CTDATA” on page 283,
“FTRANS{(*NONE | *SRC)}” on page 242, or “ALTSEQ{(*NONE | *SRC | *EXT)}”
on page 233. By associating the program data with the appropriate keyword, you
can place the groups of program data in any order after the source records.
The first entry for each input record must begin in position 1. The entire record
need not be filled with entries. Array elements associated with unused entries will
be initialized with the default value.
For more information on entering compile-time array records, see “Rules for Array
Source Records” on page 147. For more information on file translation, see “File
Translation” on page 107. For more information on alternate collating sequences,
see “Alternate Collating Sequence” on page 174.
Chapter 12. About Specifications
223
Common Entries
Common Entries
The following entries are common to all RPG specifications preceding program
data:
¹ Positions 1-5 can be used for comments.
¹ Specification type (position 6). The following letter codes can be used:
Entry
Specification Type
H
Control
F
File description
D
Definition
I
Input
C
Calculation
O
Output
P
Procedure
¹ Comment Statements
– Position 7 contains an asterisk (*). This will denote the line as a comment
line regardless of any other entry on the specification.
– Positions 6 to 80 are blank.
¹ Positions 7 to 80 are blank and position 6 contains a valid specification. This is
a valid line, not a comment, and sequence rules are enforced.
Syntax of Keywords
Keywords may have no parameters, optional parameters, or required parameters.
The syntax for keywords is as follows:
Keyword(parameter1 : parameter2)
where:
¹ Parameter(s) are enclosed in parentheses ( ).
Note: Parentheses should not be specified if there are no parameters.
¹ Colons (:) are used to separate multiple parameters.
The following notational conventions are used to show which parameters are
optional and which are required:
¹ Braces { } indicate optional parameters or optional elements of parameters.
¹ An ellipsis (...) indicates that the parameter can be repeated.
¹ A colon (:) separates parameters and indicates that more than one may be
specified. All parameters separated by a colon are required unless they are
enclosed in braces.
¹ A vertical bar (|) indicates that only one parameter may be specified for the
keyword.
¹ A blank separating keyword parameters indicates that one or more of the
parameters may be specified.
224
ILE RPG for AS/400 Reference
Common Entries
Note: Braces, ellipses, and vertical bars are not a part of the keyword syntax and
should not be entered into your source.
Table 22. Examples of Keyword Notation
|
|
|
|
|
Notation
Example of Notation
Used
Description
Example of
Source Entered
braces {}
PRTCTL (data_struct
{:*COMPAT})
Parameter data_struct is required and
parameter *COMPAT is optional.
PRTCTL
(data_struct1)
braces {}
TIME(format {separator})
Parameter format{separator} is required,
but the {separator} part of the parameter is
optional.
TIME(*HMS&)
colon (:)
RENAME(Ext_format
:Int_format)
Parameters Ext_format and Int_format are
required.
RENAME (nameE:
nameI)
ellipsis (...)
IGNORE(recformat
{:recformat...})
Parameter recformat is required and can
be specified more than once.
IGNORE
(recformat1:
recformat2:
recformat3)
vertical bar
(|)
FLTDIV{(*NO | *YES)}
Specify *NO or *YES or no parameters.
FLTDIV
blank
OPTIONS(*OMIT
*NOPASS *VARSIZE
*STRING *RIGHTADJ)
One of *OMIT, *NOPASS, *VARSIZE,
*STRING, or *RIGHTADJ is required and
more than one parameter can be optionally
specified.
OPTIONS (*OMIT:
*NOPASS:
*VARSIZE:
*STRING:
*RIGHTADJ)
Continuation Rules
The fields that may be continued are:
¹ The keywords field on the control specification
¹ The keywords field on the file description specification
¹ The keywords field on the definition specification
¹ The Extended factor-2 field on the calculation specification
¹ The constant/editword field on the output specification
¹ The Name field on the definition or the procedure specification
General rules for continuation are as follows:
¹ The continuation line must be a valid line for the specification being continued
(H, F, D, C, or O in position 6)
¹ No special characters should be used when continuing specifications across
multiple lines, except when a literal or name must be split. For example, the
following pairs are equivalent. In the first pair, the plus sign (+) is an operator,
even when it appears at the end of a line. In the second pair, the plus sign is a
continuation character.
Chapter 12. About Specifications
225
Common Entries
C
C
C
eval
eval
x = a + b
x = a +
b
C
C
C
eval
eval
x = 'abc'
x = 'ab+
c'
¹ Only blank lines, empty specification lines or comment lines are allowed
between continued lines
¹ The continuation can occur after a complete token. Tokens are
– Names (for example, keywords, file names, field names)
– Parentheses
– The separator character (:)
– Expression operators
– Built-in functions
– Special words
– Literals
¹ A continuation can also occur within a literal
– For character, date, time, and timestamp literals
- A hyphen (-) indicates continuation is in the first available position in
the continued field
- A plus (+) indicates continuation with the first non-blank character in or
past the first position in the continued field
– For graphic literals
- Either the hyphen (-) or plus (+) can be used to indicate a continuation.
- Each segment of the literal must be enclosed by shift-out and shift-in
characters.
- When the a graphic literal is assembled, only the first shift-out and the
last shift-in character will be included.
- Regardless of which continuation character is used for a graphic literal,
the literal continues with the first character after the shift-out character
on the continuation line. Spaces preceding the shift-out character are
ignored.
– For numeric literals
- No continuation character is used
- A numeric literal continues with a numeric character or decimal point on
the continuation line in the continued field
|
– For hexadecimal and UCS-2 literals
|
- Either a hyphen (-) or a plus (+) can be used to indicate a continuation
|
|
- The literal will be continued with the first non-blank character on the
next line
¹ A continuation can also occur within a name in free-format entries
226
ILE RPG for AS/400 Reference
Common Entries
– In the name entry for Definition and Procedure specifications. For more
information on continuing names in the name entry, see “Definition and
Procedure Specification Name Field” on page 229.
– In the keywords entry for File and Definition specifications.
– In the extended factor 2 entry of Calculation specifications.
In all cases, the name is continued by coding an ellipsis (...) at the end of the
partial name, with no intervening blanks.
Example
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D
Keywords-cont++++++++++++++++++++++++
* Define a 10 character field with a long name.
* The second definition is a pointer initialized to the address
* of the variable with the long name.
D QuiteLongFieldNameThatCannotAlwaysFitInOneLine...
D
S
10A
D Ptr
S
*
inz(%addr(QuiteLongFieldName...
D
ThatCannotAlways...
D
FitInOneLine))
D ShorterName
S
5A
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++++
C
Extended-factor2-++++++++++++++++++++++++++++
* Use the long name in an expression
* Note that you can split the name wherever it is convenient.
C
EVAL
QuiteLongFieldName...
C
ThatCannotAlwaysFitInOneLine = 'abc'
* You can split any name this way
C
EVAL
P...
C
tr = %addr(Shorter...
C
Name)
Control Specification Keyword Field
The rule for continuation on the control specification is:
¹ The specification continues on or past position 7 of the next control specification
Example
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
H DATFMT(
H
*MDY&
H
)
Chapter 12. About Specifications
227
Common Entries
File Description Specification Keyword Field
The rules for continuation on the file description specification are:
¹ The specification continues on or past position 44 of the next file description
specification
¹ Positions 7-43 of the continuation line must be blank
Example
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords+++++++++++++++++++++++++++++
F.....................................Keywords+++++++++++++++++++++++++++++
F
EXTIND
F
(
F
*INU1
F
)
Definition Specification Keyword Field
The rules for continuation of keywords on the definition specification are:
¹ The specification continues on or past position 44 of the next Definition specification dependent on the continuation character specified
¹ Positions 7-43 of the continuation line must be blank
Example
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D
Keywords-cont++++++++++++++++++++++++
DMARY
C
CONST(
D
'Mary had a little lamb, its * Only a comment or a completely blank line is allowed in here
D
fleece was white as snow.'
D
)
* Numeric literal, continues with the first non blank in/past position 44
*
DNUMERIC
C
12345
D
67
* Graphic named constant, must have shift-out in/past position 44
DGRAF
C
G'oAABBCCDDi+
D
oEEFFGGi'
Calculation Specification Extended Factor-2
The rules for continuation on the Calculation specification are:
¹ The specification continues on or past position 36 of the next calculation specification
¹ Positions 7-35 of the continuation line must be blank
Example
228
ILE RPG for AS/400 Reference
Common Entries
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++++
C
Extended-factor2-++++++++++++++++++++++++++++
C
EVAL
MARY='Mary had a little lamb, its +
* Only a comment or a completely blank line is allowed in here
C
fleece was white as snow.'
*
* Arithmetic expressions do not have continuation characters.
* The '+' sign below is the addition operator, not a continuation
* character.
C
C
EVAL
A = (B*D)/ C +
C
24
* The first use of '+' in this example is the concatenation
* operator. The second use is the character literal continuation.
C
EVAL
ERRMSG = NAME +
C
' was not found +
C
in the file.'
Output Specification Constant/Editword Field
The rules for continuation on the output specification are:
¹ The specification continues on or past position 53 of the next output specification
¹ Positions 7-52 of the continuation line must be blank
Example
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
O.............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat+++
O
Continue Constant/editword+++
O
80 'Mary had a little lamb, its*
* Only a comment or a completely blank line is allowed in here
O
fleece was white as snow.'
Definition and Procedure Specification Name Field
The rules for continuation of the name on the definition and procedure specifications are:
¹ Continuation rules apply for names longer than 15 characters. Any name (even
one with 15 characters or fewer) can be continued on multiple lines by coding
an ellipsis (...) at the end of the partial name.
¹ A name definition consists of the following parts:
1. Zero or more continued name lines. Continued name lines are identified as
having an ellipsis as the last non-blank characters in the entry. The name
must begin within positions 7 - 21 and may end anywhere up to position 77
(with an ellipsis ending in position 80). There cannot be blanks between the
start of the name and the ellipsis (...) characters. If any of these conditions
is not true, the line is considered to be a main definition line.
Chapter 12. About Specifications
229
Common Entries
2. One main definition line containing name, definition attributes, and
keywords. If a continued name line is coded, the name entry of the main
definition line may be left blank.
3. Zero or more keyword continuation lines.
Example
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D
Keywords-cont++++++++++++++++++++++++
* Long name without continued name lines:
D RatherLongName S
10A
* Long name using 1 continued name line:
D NameThatIsEvenLonger...
D
C
'This is the constant D
that the name represents.'
* Long name using 1 continued name line:
D NameThatIsSoLongItMustBe...
D
Continued
S
10A
* Compile-time arrays may have long names:
D CompileTimeArrayContainingDataRepresentingTheNamesOfTheMonthsOf...
D TheYearInGermanLanguage...
D
S
20A
DIM(12) CTDATA PERRCD(1)
* Long name using 3 continued name lines:
D ThisNameIsSoMuchLongerThanThe...
D
PreviousNamesThatItMustBe...
D
ContinuedOnSeveralSpecs...
D
PR
10A
D parm_1
10A
VALUE
*
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++++
C
Extended-factor2-++++++++++++++++++++++++++++
* Long names defined on calc spec:
C
LongTagName
TAG
C
*LIKE
DEFINE
RatherLongNameQuiteLongName
+5
*
PName+++++++++++..B...................Keywords+++++++++++++++++++++++++++++
PContinuedName+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
* Long name specified on Procedure spec:
P ThisNameIsSoMuchLongerThanThe...
P
PreviousNamesThatItMustBe...
P
ContinuedOnSeveralSpecs...
P
B
D ThisNameIsSoMuchLongerThanThe...
D
PreviousNamesThatItMustBe...
D
ContinuedOnSeveralSpecs...
D
PI
10A
D parm_1
10A
VALUE
230
ILE RPG for AS/400 Reference
Control-Specification Statement
Chapter 13. Control Specifications
The control-specification statements, identified by an H in position 6, provide information about generating and running programs. However, there are three different
ways in which this information can be provided to the compiler and the compiler
searches for this information in the following order:
1. A control specification included in your source
2. A data area named RPGLEHSPEC in *LIBL
3. A data area named DFTLEHSPEC in QRPGLE
Once one of these sources is found, the values are assigned and keywords that
are not specified are assigned their default values.
See the description of the individual entries for their default values.
Note: Compile-option keywords do not have default values. The keyword value is
initialized with the value you specify for the CRTBNDRPG or CRTRPGMOD
command.
TIP
The control specification keywords apply at the module level. This means that if
there is more than one procedure coded in a module, the values specified in the
control specification apply to all procedures.
Using a Data Area as a Control Specification
Use the CL command CRTDTAARA (Create Data Area) to create a data area
defined as type *CHAR. (See the CL Reference (Abridged) for a description of the
Create Data Area command.) Enter the keywords and their possible parameters
that are to be used in the Initial Value field of the command.
For example, to create an RPGLEHSPEC data area that will specify a default date
format of *YMD, and a default date separator /, you would enter:
CRTDTAARA DTAARA(MYLIB/RPGLEHSPEC)
TYPE(*CHAR)
LEN(80)
VALUE('datfmt(*ymd) datedit(*ymd/)')
The data area can be whatever size is required to accommodate the keywords
specified. The entire length of the data area can only contain keywords.
Control-Specification Statement
The control specification consists solely of keywords. The keywords can be placed
anywhere between positions 7 and 80. Positions 81-100 can be used for comments.
 Copyright IBM Corp. 1994, 1999
231
Control-Specification Keywords
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Comments++++++++++++
Figure 100. Control-Specification Layout
The following is an example of a control specification.
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
H ALTSEQ(*EXT) CURSYM('$') DATEDIT(*MDY) DATFMT(*MDY/) DEBUG(*YES)
H DECEDIT('.') FORMSALIGN(*YES) FTRANS(*SRC) DFTNAME(name)
H TIMFMT(*ISO)
H COPYRIGHT('(C) Copyright ABC Programming - 1995')
Position 6 (Form Type)
An H must appear in position 6 to identify this line as the control specification.
Positions 7-80 (Keywords)
The control-specification keywords are used to determine how the program will deal
with devices and how certain types of information will be represented.
The control-specification keywords also include compile-option keywords that override the default or specified options on the CRTBNDRPG and CRTRPGMOD commands. These keywords determine the compile options to be used on every
compile of the program.
Control-Specification Keywords
Control-specification keywords may have no parameters, optional parameters, or
required parameters. The syntax for keywords is as follows:
Keyword(parameter1 : parameter2)
where:
¹ Parameter(s) are enclosed in parentheses ( ).
Note: Do not specify parentheses if there are no parameters.
¹ Colons (:) are used to separate multiple parameters.
The following notational conventions are used to show which parameters are
optional and which are required:
¹ Braces { } indicate optional parameters or optional elements of parameters.
¹ An ellipsis (...) indicates that the parameter can be repeated.
¹ A colon (:) separates parameters and indicates that more than one may be
specified. All parameters separated by a colon are required unless they are
enclosed in braces.
¹ A vertical bar (|) indicates that only one parameter may be specified for the
keyword.
232
ILE RPG for AS/400 Reference
Control-Specification Keywords
¹ A blank separating keyword parameters indicates that one or more of the
parameters may be specified.
Note: Braces, ellipses, and vertical bars are not a part of the keyword syntax and
should not be entered into your source.
If additional space is required for control-specification keywords, the keyword field
can be continued on subsequent lines. See “Control-Specification Statement” on
page 231 and “Control Specification Keyword Field” on page 227.
ACTGRP(*NEW | *CALLER | 'activation-group-name')
The ACTGRP keyword allows you to specify the activation group the program is
associated with when it is called. If ACTGRP(*NEW) is specified, then the program
is activated into a new activation group. If ACTGRP(*CALLER) is specified, then
the program is activated into the caller's activation group. If an activation-groupname is specified, then that name is used when this program is called.
If the ACTGRP keyword is not specified, then the value specified on the command
is used.
The ACTGRP keyword is valid only if the CRTBNDRPG command is used.
You cannot use the ACTGRP or BNDDIR keywords when creating a program with
DFTACTGRP(*YES).
ALTSEQ{(*NONE | *SRC | *EXT)}
The ALTSEQ keyword indicates whether an alternate collating sequence is used, if
so, whether it is internal or external to the source. The following list shows what
happens for the different possible keyword and parameter combinations.
Keyword/Parameter Collating Sequence Used
ALTSEQ not specified
Normal collating sequence
ALTSEQ(*NONE)
Normal collating sequence
ALTSEQ, no parameters
Alternate collating sequence specified in source
ALTSEQ(*SRC)
Alternate collating sequence specified in source
ALTSEQ(*EXT)
Alternate collating sequence specified by the SRTSEQ and LANGID
command parameters or keywords.
If ALTSEQ is not specified or specified with *NONE or *EXT, an alternate collating
sequence table must not be specified in the program.
Chapter 13. Control Specifications
233
Control-Specification Keywords
ALWNULL(*NO | *INPUTONLY | *USRCTL)
The ALWNULL keyword specifies how you will use records containing null-capable
fields from externally described database files.
If ALWNULL(*NO) is specified, then you cannot process records with null-value
fields from externally described files. If you attempt to retrieve a record containing
null values, no data in the record will be accessible and a data-mapping error will
occur.
If ALWNULL(*INPUTONLY) is specified, then you can successfully read records
with null-capable fields containing null values from externally described input-only
database files. When a record containing null values is retrieved, no data-mapping
errors will occur and the database default values are placed into any fields that
contain null values. However, you cannot do any of the following:
¹ Use null-capable key fields
¹ Create or update records containing null-capable fields
¹ Determine whether a null-capable field is actually null while the program is
running
¹ Set a null-capable field to be null.
If ALWNULL(*USRCTL) is specified, then you can read, write, and update records
with null values from externally described database files. Records with null keys
can be retrieved using keyed operations. You can determine whether a null-capable
field is actually null, and you can set a null-capable field to be null for output or
update. You are responsible for ensuring that fields containing null values are used
correctly.
If the ALWNULL keyword is not specified, then the value specified on the command
is used.
For more information, see “Database Null Value Support” on page 198
AUT(*LIBRCRTAUT | *ALL | *CHANGE | *USE | *EXCLUDE |
'authorization-list-name')
The AUT keyword specifies the authority given to users who do not have specific
authority to the object, who are not on the authorization list, and whose user group
has no specific authority to the object. The authority can be altered for all users or
for specified users after the object is created with the CL commands Grant Object
Authority (GRTOBJAUT) or Revoke Object Authority (RVKOBJAUT).
If AUT(*LIBRCRTAUT) is specified, then the public authority for the object is taken
from the CRTAUT keyword of the target library (the library that contains the object).
The value is determined when the object is created. If the CRTAUT value for the
library changes after the create, the new value will not affect any existing objects.
If AUT(*ALL) is specified, then authority is provided for all operations on the object,
except those limited to the owner or controlled by authorization list management
authority. The user can control the object's existence, specify this security for it,
change it, and perform basic functions on it, but cannot transfer its ownership.
234
ILE RPG for AS/400 Reference
Control-Specification Keywords
If AUT(*CHANGE) is specified, then it provides all data authority and the authority
to perform all operations on the object except those limited to the owner or controlled by object authority and object management authority. The user can change
the object and perform basic functions on it.
If AUT(*USE) is specified, then it provides object operational authority and read
authority; that is, authority for basic operations on the object. The user is prevented
from changing the object.
If AUT(*EXCLUDE) is specified, then it prevents the user from accessing the object.
The authorization-list-name is the name of an authorization list of users and authorities to which the object is added. The object will be secured by this authorization
list, and the public authority for the object will be set to *AUTL. The authorization
list must exist on the system at compilation time.
If the AUT keyword is not specified, then the value specified on the command is
used.
BNDDIR('binding-directory-name' {:'binding-directory-name'...})
The BNDDIR keyword specifies the list of binding directories that are used in
symbol resolution.
A binding directory name can be qualified by a library name followed by a slash
delimiter ('library-name/binding-directory-name'). The library name is the name of
the library to be searched. If the library name is not specified, *LIBL is used to find
the binding directory name. When creating a program using CRTBNDRPG, the
library list is searched at the time of the compile. When creating a module using
CRTRPGMOD, the library list is searched when the module is used to create a
program or service program.
If the BNDDIR keyword is not specified, then the value specified on the command
is used.
You cannot use the BNDDIR or ACTGRP command parameters or keywords when
creating a program with DFTACTGRP(*YES).
|
|
|
|
|
CCSID(*GRAPH : parameter | *UCS2 : number)
This keyword sets the default graphic (*GRAPH) and UCS-2 (*UCS2) CCSIDs for
the module. These defaults are used for literals, compile-time data, programdescribed input and output fields, and data definitions that do not have the CCSID
keyword coded.
|
|
CCSID(*GRAPH : *IGNORE | *SRC | number)
Sets the default graphic CCSID for the module. The possible values are:
|
|
|
|
*IGNORE
This is the default. No conversions are allowed between graphic and
UCS-2 fields in the module. The %GRAPH built-in function cannot
be used.
|
|
|
*SRC
The graphic CCSID associated with the CCSID of the source file will
be used.
Chapter 13. Control Specifications
235
Control-Specification Keywords
|
|
|
number
A graphic CCSID. A valid graphic CCSID is 65535 or a CCSID with
the EBCDIC double-byte encoding scheme (X'1200').
|
|
|
CCSID(*UCS2 : number)
Sets the default UCS-2 CCSID for the module. If this keyword is not
specified, the default UCS-2 CCSID is 13488.
|
|
number must be a UCS-2 CCSID. A valid UCS-2 CCSID has the
UCS-2 encoding scheme (x'7200').
|
If CCSID(*GRAPH : *SRC) or CCSID(*GRAPH : number) is specified:
|
|
¹ Graphic and UCS-2 fields in externally-described data structures will use the
CCSID in the external file.
|
|
|
|
¹ Program-described graphic or UCS-2 fields will default to the graphic or UCS-2
CCSID of the module, respectively. This specification can be overridden by
using the CCSID(number) keyword on the definition of the field. (See
“CCSID(number | *DFT)” on page 282.)
|
|
¹ Program-described graphic or UCS-2 input and output fields and keys are
assumed to have the module's default CCSID.
COPYNEST(number)
The COPYNEST keyword specifies the maximum depth to which nesting can occur
for /COPY directives. The depth must be greater than or equal to 1 and less than
or equal to 2048. The default depth is 32.
COPYRIGHT('copyright string')
The COPYRIGHT keyword provides copyright information that can be seen using
the DSPMOD, DSPPGM, or DSPSRVPGM commands. The copyright string is a
character literal with a maximum length of 256. The literal may be continued on a
continuation specification. (See “Continuation Rules” on page 225 for rules on
using continuation lines.) If the COPYRIGHT keyword is not specified, copyright
information is not added to the created module or program.
TIP
To see the copyright information for a module, use the command:
DSPMOD mylib/mymod DETAIL(*COPYRIGHT)
For a program, use the DSPPGM command with DETAIL(*COPYRIGHT). This
information includes the copyright information from all modules bound into the
program.
Similarly, DSPSRVPGM DETAIL(*COPYRIGHT) gives the copyright information
for all modules in a service program.
236
ILE RPG for AS/400 Reference
Control-Specification Keywords
CURSYM('sym')
The CURSYM keyword specifies a character used as a currency symbol in editing.
The symbol must be a single character enclosed in quotes. Any character in the
RPG character set (see Chapter 1, “Symbolic Names and Reserved Words” on
page 3) may be used except:
¹ 0 (zero)
¹ * (asterisk)
¹ , (comma)
¹ & (ampersand)
¹ . (period)
¹ − (minus sign)
¹ C (letter C)
¹ R (letter R)
¹ Blank
If the keyword is not specified, $ (dollar sign) will be used as the currency symbol.
CVTOPT(*{NO}DATETIME *{NO}GRAPHIC *{NO}VARCHAR
*{NO}VARGRAPHIC)
The CVTOPT keyword is used to determine how the ILE RPG compiler handles
date, time, timestamp, graphic data types, and variable-length data types that are
retrieved from externally described database files.
You can specify any or all of the data types in any order. However, if a data type is
specified, the *NOxxxx parameter for the same data type cannot also be used, and
vice versa. For example, if you specify *GRAPHIC you cannot also specify
*NOGRAPHIC, and vice versa. Separate the parameters with a colon. A parameter
cannot be specified more than once.
Note: If the keyword CVTOPT does not contain a member from a pair, then the
value specified on the command for this particular data type will be used.
For example, if the keyword CVTOPT(*DATETIME : *NOVARCHAR :
*NOVARGRAPHIC) is specified on the Control specification, then for the
pair (*GRAPHIC, *NOGRAPHIC), whatever was specified implicitly or explicitly on the command will be used.
If *DATETIME is specified, then date, time, and timestamp data types are declared
as fixed-length character fields.
If *NODATETIME is specified, then date, time, and timestamp data types are not
converted.
If *GRAPHIC is specified, then double-byte character set (DBCS) graphic data
types are declared as fixed-length character fields.
If *NOGRAPHIC is specified, then double-byte character set (DBCS) graphic types
are not converted.
If *VARCHAR is specified, then variable-length character data types are declared
as fixed-length character fields.
Chapter 13. Control Specifications
237
Control-Specification Keywords
If *NOVARCHAR is specified, then variable-length character data types are not
converted.
If *VARGRAPHIC is specified, then variable-length double-byte character set
(DBCS) graphic data types are declared as fixed-length character fields.
If *NOVARGRAPHIC is specified, then variable-length double-byte character set
(DBCS) graphic data types are not converted.
If the CVTOPT keyword is not specified, then the values specified on the command
are used.
DATEDIT(fmt{separator})
The DATEDIT keyword specifies the format of numeric fields when using the Y edit
code. The separator character is optional. The value (fmt) can be *DMY, *MDY, or
*YMD. The default separator is /. A separator character of & (ampersand) may be
used to specify a blank separator.
DATFMT(fmt{separator})
The DATFMT keyword specifies the internal date format for date literals and the
default internal format for date fields within the program. You can specify a different
internal date format for a particular field by specifying the format with the DATFMT
keyword on the definition specification for that field.
If the DATFMT keyword is not specified, the *ISO format is assumed. For more
information on internal formats, see “Internal and External Formats” on page 159.
Table 13 on page 186 describes the various date formats and their separators.
DEBUG{(*NO | *YES)}
The DEBUG keyword determines whether DUMP operations are performed and
whether unused externally described input fields are moved from the buffer during
input operations.
DUMP operations are performed if either DEBUG or DEBUG(*YES) is specified. If
this keyword is not specified or specified with *NO, DUMP operations are not performed.
Normally, externally described input fields are only read during input operations if
the field is otherwise used within the program. If DEBUG or DEBUG(*YES) is specified, all externally described input fields will be entered even if they are not used in
the program.
DECEDIT(*JOBRUN | 'value')
The DECEDIT keyword specifies the character used as the decimal point for edited
decimal numbers and whether or not leading zeros are printed.
If *JOBRUN is specified, the DECFMT value associated with the job at runtime is
used. The possible job decimal formats are listed in the following table:
238
ILE RPG for AS/400 Reference
Control-Specification Keywords
Table 23. DECEDIT with *JOBRUN
Job Decimal
Format
Decimal Point
Print Leading
Zeros
Edited Decimal
Number
blank
period (.)
No
.123
I
comma (,)
No
,123
J
comma (,)
Yes
0,123
If a value is specified, then the edited decimal numbers are printed according to the
following possible values:
Table 24. DECEDIT with 'value'
'Value'
Decimal Point
Print Leading
Zeros
Edited Decimal
Number
'.'
period (.)
No
.123
','
comma (,)
No
,123
'0.'
period (.)
Yes
0.123
'0,'
comma (,)
Yes
0,123
If DECEDIT is not specified, a period (.) is used for editing numeric values.
Note: Zeros to the right of a decimal point are always printed.
DFTACTGRP(*YES | *NO)
The DFTACTGRP keyword specifies the activation group in which the created
program will run when it is called.
If *YES is specified, then this program will always run in the default activation
group, which is the activation group where all original program model (OPM) programs are run. This allows ILE RPG programs to behave like OPM RPG programs
in the areas of file sharing, file scoping, RCLRSC, and handling of unmonitored
exceptions. ILE static binding is not available when a program is created with
DFTACTGRP(*YES). This means that you cannot use the BNDDIR or ACTGRP
command parameters or keywords when creating this program. In addition, any call
operation in your source must call a program and not a procedure.
DFTACTGRP(*YES) is useful when attempting to move an application on a
program-by-program basis to ILE RPG.
If *NO is specified, then the program is associated with the activation group specified by the ACTGRP command parameter or keyword and static binding is allowed.
DFTACTGRP(*NO) is useful when you intend to take advantage of ILE concepts;
for example, running in a named activation group or binding to a service program.
If the DFTACTGRP keyword is not specified, then the value specified on the
command is used.
The DFTACTGRP keyword is valid only if the CRTBNDRPG command is used.
Chapter 13. Control Specifications
239
Control-Specification Keywords
DFTNAME(rpg_name)
The DFTNAME keyword specifies a default program or module name. When
*CTLSPEC is specified on the create command, the rpg_name is used as the
program or module name. If rpg_name is not specified, then the default name is
RPGPGM or RPGMOD for a program or module respectively. The RPG rules for
names (see “Symbolic Names” on page 3)apply.
ENBPFRCOL(*PEP | *ENTRYEXIT | *FULL)
The ENBPFRCOL keyword specifies whether performance collection is enabled.
If *PEP is specified, then performance statistics are gathered on the entry and exit
of the program-entry procedure only. This applies to the actual program-entry procedure for an object, not to the main procedure of the object within the object.
If *ENTRYEXIT is specified, then performance statistics are gathered on the entry
and exit of all procedures of the object.
If *FULL is specified, then performance statistics are gathered on entry and exit of
all procedures. Also, statistics are gathered before and after each call to an
external procedure.
If the ENBPFRCOL keyword is not specified, then the value specified on the
command is used.
EXPROPTS(*MAXDIGITS | *RESDECPOS)
The EXPROPTS (expression options) keyword specifies the type of precision rules
to be used for an entire program. If not specified or specified with *MAXDIGITS, the
default precision rules apply. If EXPROPTS is specified, with *RESDECPOS, the
"Result Decimal Position" precision rules apply and force intermediate results in
expressions to have no fewer decimal positions than the result.
Note: Operation code extenders R and M are the same as
EXPROPTS(*RESDECPOS) and EXPROPTS(*MAXDIGITS) respectively,
but for single free-form expressions.
EXTBININT{(*NO | *YES)}
The EXTBININT keyword is used to process externally described fields with binary
external format and zero decimal positions as if they had an external integer format.
If not specified or specified with *NO, then an externally described binary field is
processed with an external binary format. If EXTBININT is specified, optionally with
*YES, then an externally described field is processed as follows:
DDS Definition RPG external format
B(n,0) where 1 ≤ n ≤ 4
I(5)
B(n,0) where 5 ≤ n ≤ 9
I(10)
By specifying the EXTBININT keyword, your program can make use of the full
range of DDS binary values available. (The range of DDS binary values is the
same as for signed integers: -32768 to 32767 for a 5-digit field or -2147483648 to
2147483647 for a 10-digit field.)
240
ILE RPG for AS/400 Reference
Control-Specification Keywords
Note: When the keyword EXTBININT is specified, any externally described subfields that are binary with zero decimal positions will be defined with an
internal integer format.
FIXNBR(*{NO}ZONED *{NO}INPUTPACKED)
The FIXNBR keyword specifies whether decimal data that is not valid is fixed by
the compiler.
You can specify any or all of the data types in any order. However, if a decimal
data type is specified, the *NOxxxx parameter for the same data type cannot also
be used, and vice versa. For example, if you specify *ZONED you cannot also
specify *NOZONED, and vice versa. Separate the parameters with a colon. A
parameter cannot be specified more than once.
Note: If the keyword FIXNBR does not contain a member from a pair, then the
value specified on the command for this particular data type will be used.
For example, if the keyword FIXNBR(*NOINPUTPACKED) is specified on
the Control specification, then for the pair (*ZONED, *NOZONED), whatever
was specified implicitly or explicitly on the command will be used.
If *ZONED is specified, then zoned decimal data that is not valid will be fixed by the
compiler on the conversion to packed data. Blanks in numeric fields will be treated
as zeros. Each decimal digit will be checked for validity. If a decimal digit is not
valid, it is replaced with zero. If a sign is not valid, the sign will be forced to a
positive sign code of hex 'F'. If the sign is valid, it will be changed to either a positive sign hex 'F' or a negative sign hex 'D', as appropriate. If the resulting packed
data is not valid, it will not be fixed.
If *NOZONED is specified, then zoned decimal data is not fixed by the compiler on
the conversion to packed data and will result in decimal errors during runtime if
used.
If *INPUTPACKED is specified, then the internal variable will be set to zero if
packed decimal data that is not valid is encountered while processing input specifications.
If *NOINPUTPACKED is specified, then decimal errors will occur if packed decimal
data that is not valid is encountered while processing input specifications.
If the FIXNBR keyword is not specified, then the values specified on the command
are used.
FLTDIV{(*NO | *YES)}
The FLTDIV keyword indicates that all divide operations within expressions are
computed in floating point and return a value of type float. If not specified or specified with *NO, then divide operations are performed in packed-decimal format
(unless one of the two operands is already in float format).
If FLTDIV is specified, optionally with *YES, then all divide operations are performed in float format (guaranteeing that the result always has 15 digits of precision).
Chapter 13. Control Specifications
241
Control-Specification Keywords
FORMSALIGN{(*NO | *YES)}
The FORMSALIGN keyword indicates that the first line of an output file conditioned
with the 1P indicator can be printed repeatedly, allowing you to align the printer. If
not specified or specified with *NO, no alignment will be performed. If specified,
optionally with *YES, first page forms alignment will occur.
Rules for Forms Alignment
¹ The records specified on Output Specifications for a file with a device entry for
a printer type device conditioned by the first page indicator (1P) may be written
as many times as desired. The line will print once. The operator will then have
the option to print the line again or continue with the rest of the program.
¹ All spacing and skipping specified will be performed each time the line is
printed.
¹ When the option to continue with the rest of the program is selected, the line
will not be reprinted.
¹ The function may be performed for all printer files.
¹ If a page field is specified, it will be incremented only the first time the line is
printed.
¹ When the continue option is selected, the line count will be the same as if the
function were performed only once when line counter is specified.
FTRANS{(*NONE | *SRC)}
The FTRANS keyword specifies whether file translation will occur. If specified,
optionally with *SRC, file translation will take place and the translate table must be
specified in the program. If not specified or specified with *NONE, no file translation
will take place and the translate table must not be present.
GENLVL(number)
The GENLVL keyword controls the creation of the object. The object is created if all
errors encountered during compilation have a severity level less than or equal to
the generation severity level specified. The value must be between 0 and 20 inclusive. For errors greater than severity 20, the object will not be created.
If the GENLVL keyword is not specified, then the value specified on the command
is used.
INDENT(*NONE | 'character-value')
The INDENT keyword specifies whether structured operations should be indented
in the source listing for enhanced readability. It also specifies the characters that
are used to mark the structured operation clauses.
Note: Any indentation that you request here will not be reflected in the listing
debug view that is created when you specify DBGVIEW(*LIST).
If *NONE is specified, structured operations will not be indented in the source
listing.
If character-value is specified, the source listing is indented for structured operation
clauses. Alignment of statements and clauses are marked using the characters you
choose. You can choose any character literal up to 2 characters in length.
242
ILE RPG for AS/400 Reference
Control-Specification Keywords
Note: The indentation may not appear as expected if there are errors in the
source.
If the INDENT keyword is not specified, then the value specified on the command is
used.
|
|
|
|
|
|
INTPREC(10 | 20)
The INTPREC keyword is used to specify the decimal precision of integer and
unsigned intermediate values in binary arithmetic operations in expressions.
Integer and unsigned intermediate values are always maintained in 8-byte format.
This keyword affects only the way integer and unsigned intermediate values are
converted to decimal format when used in binary arithmetic operations (+, -, *, /).
|
|
|
|
INTPREC(10), the default, indicates a decimal precision of 10 digits for integer and
unsigned operations. However, if at least one operand in the expression is an
8-byte integer or unsigned field, the result of the expression has a decimal precision of 20 digits regardless of the INTPREC value.
|
|
INTPREC(20) indicates that the decimal precision of integer and unsigned operations is 20 digits.
LANGID(*JOBRUN | *JOB | 'language-identifier')
The LANGID keyword indicates which language identifier is to be used when the
sort sequence is *LANGIDUNQ or *LANGIDSHR. The LANGID keyword is used in
conjunction with the SRTSEQ command parameter or keyword to select the sort
sequence table.
If *JOBRUN is specified, then the LANGID value associated with the job when the
RPG object is executed is used.
If *JOB is specified, then the LANGID value associated with the job when the RPG
object is created is used.
A language identifier can be specified, for example, 'FRA' for French and 'DEU' for
German.
If the LANGID keyword is not specified, then the value specified on the command is
used.
NOMAIN
The NOMAIN keyword indicates that there is no main procedure in this module. It
also means that the module in which it is coded cannot be an entry module. Consequently, if NOMAIN is specified, then you cannot use the CRTBNDRPG command
to create a program. Instead you must either use the CRTPGM command to bind
the module with NOMAIN specified to another module that has a program entry
procedure or you must use the CRTSRVPGM command.
When NOMAIN is specified, only the *INIT portion of the cycle is generated for the
module. This means that the following types of specifications are not allowed:
¹ Primary and secondary files
¹ Detail and total output
¹ Executable calculations
Chapter 13. Control Specifications
243
Control-Specification Keywords
|
|
|
|
|
|
|
OPENOPT (*NOINZOFL | *INZOFL)
For a program that has one or more printer files defined with an overflow indicator
(OA-OG or OV), the OPENOPT keyword specifies whether the overflow indicator
should be reset to *OFF when the file is opened. If the OPENOPT keyword is specified, with *NOINZOFL, the overflow indicator will remain unchanged when the
associated printer file is opened. If not specified or specified with *INZOFL, the
overflow indicator will be set to *OFF when the associated printer file is opened.
OPTIMIZE(*NONE | *BASIC | *FULL)
The OPTIMIZE keyword specifies the level of optimization, if any, of the object.
If *NONE is specified, then the generated code is not optimized. This is the fastest
in terms of translation time. It allows you to display and modify variables while in
debug mode.
If *BASIC is specified, it performs some optimization on the generated code. This
allows user variables to be displayed but not modified while the program is in
debug mode.
If *FULL is specified, then the most efficient code is generated. Translation time is
the longest. In debug mode, user variables may not be modified but may be displayed, although the presented values may not be the current values.
If the OPTIMIZE keyword is not specified, then the value specified on the command
is used.
OPTION(*{NO}XREF *{NO}GEN *{NO}SECLVL *{NO}SHOWCPY
*{NO}EXPDDS *{NO}EXT *{NO}SHOWSKP) *{NO}SRCSTMT)
*{NO}DEBUGIO)
The OPTION keyword specifies the options to use when the source member is
compiled.
You can specify any or all of the options in any order. However, if a compile option
is specified, the *NOxxxx parameter for the same compile option cannot also be
used, and vice versa. For example, if you specify *XREF you cannot also specify
*NOXREF, and vice versa. Separate the options with a colon. You cannot specify
an option more than once.
Note: If the keyword OPTION does not contain a member from a pair, then the
value specified on the command for this particular option will be used. For
example, if the keyword OPTION(*XREF : *NOGEN : *NOSECLVL :
*SHOWCPY) is specified on the Control specification, then for the pairs,
(*EXT, *NOEXT), (*EXPDDS, *NOEXPDDS) and (*SHOWSKP,
*NOSHOWSKP), whatever was specified implicitly or explicitly on the
command will be used.
If *XREF is specified, a cross-reference listing is produced (when appropriate) for
the source member. *NOXREF indicates that a cross-reference listing is not
produced.
If *GEN is specified, a program object is created if the highest severity level
returned by the compiler does not exceed the severity specified in the GENLVL
option. *NOGEN does not create an object.
244
ILE RPG for AS/400 Reference
Control-Specification Keywords
If *SECLVL is specified, second-level message text is printed on the line following
the first-level message text in the Message Summary section. *NOSECLVL does
not print second-level message text on the line following the first-level message
text.
If *SHOWCPY is specified, the compiler listing shows source records of members
included by the /COPY compiler directive. *NOSHOWCPY does not show source
records of members included by the /COPY compiler directive.
If *EXPDDS is specified, the expansion of externally described files in the listing
and key field information is displayed. *NOEXPDDS does not show the expansion
of externally described files in the listing or key field information.
If *EXT is specified, the external procedures and fields referenced during the
compile are included on the listing. *NOEXT does not show the list of external procedures and fields referenced during compile on the listing.
If *SHOWSKP is specified, then all statements in the source part of the listing are
displayed, regardless of whether or not the compiler has skipped them.
*NOSHOWSKP does not show skipped statements in the source part of the listing.
The compiler skips statements as a result of /IF, /ELSEIF, or /ELSE directives.
|
|
If *SRCSTMT is specified, statement numbers for the listing are generated from the
source ID and SEU sequence numbers as follows:
|
stmt_num = source_ID * 1000000 + source_SEU_sequence_number
|
|
|
|
|
For example, the main source member has a source ID of 0. If the first line in the
source file has sequence number 000100, then the statement number for this specification would be 100. A line from a /COPY file member with source ID 27 and
source sequence number 000100 would have statement number 27000100.
*NOSRCSTMT indicates that line numbers are assigned sequentially.
|
|
|
If *DEBUGIO is specified, breakpoints are generated for all input and output specifications. *NODEBUGIO indicates that no breakpoints are to be generated for these
specifications.
If the OPTION keyword is not specified, then the values specified on the command
are used.
PRFDTA(*NOCOL | *COL)
The PRFDTA keyword specifies whether the collection of profiling data is enabled.
If *NOCOL is specified, the collection of profiling data is not enabled for this object.
If *COL is specified, the collection of profiling is enabled for this object. *COL can
be specified only when the optimization level of the object is *FULL.
If the PRFDTA keyword is not specified, then the value specified on the command
is used.
Chapter 13. Control Specifications
245
Control-Specification Keywords
SRTSEQ(*HEX | *JOB | *JOBRUN | *LANGIDUNQ | *LANGIDSHR |
'sort-table-name')
The SRTSEQ keyword specifies the sort sequence table that is to be used in the
ILE RPG source program.
If *HEX is specified, no sort sequence table is used.
If *JOB is specified, the SRTSEQ value for the job when the *PGM is created is
used.
If *JOBRUN is specified, the SRTSEQ value for the job when the *PGM is run is
used.
If *LANGIDUNQ is specified, a unique-weight table is used. This special value is
used in conjunction with the LANGID command parameter or keyword to determine
the proper sort sequence table.
If *LANGIDSHR is specified, a shared-weight table is used. This special value is
used in conjunction with the LANGID command parameter or keyword to determine
the proper sort sequence table.
A sort table name can be specified to indicate the name of the sort sequence table
to be used with the object. It can also be qualified by a library name followed by a
slash delimiter ('library-name/sort-table-name'). The library-name is the name of the
library to be searched. If a library name is not specified, *LIBL is used to find the
sort table name.
If the SRTSEQ keyword is not specified, then the value specified on the command
is used.
TEXT(*SRCMBRTXT | *BLANK | 'description')
The TEXT keyword allows you to enter text that briefly describes the object and its
function. The text is used when creating the object and appears when object information is displayed.
If *SRCMBRTXT is specified, the text of the source member is used.
If *BLANK is specified, no text will appear.
If a literal is specified, it can be a maximum of 50 characters and must be enclosed
in apostrophes. (The apostrophes are not part of the 50-character string.)
If the TEXT keyword is not specified, then the value specified on the command is
used.
|
|
|
|
|
THREAD(*SERIALIZE)
The THREAD(*SERIALIZE) keyword indicates that the ILE RPG module created
may run in a multithreaded environment, safely. Access to the procedures in the
module is serialized. When called in a multithreaded environment, any code within
the module can be used by at most one thread at a time.
|
|
Normally, running an application in multiple threads can improve the performance of
the application. In the case of ILE RPG, this is not true in general. In fact, the per-
246
ILE RPG for AS/400 Reference
Control-Specification Keywords
|
|
|
formance of a multithreaded application could be worse than that of a single-thread
version when the thread-safety is achieved by serialization of the procedures at the
module level.
|
|
|
|
|
Running ILE RPG procedures in a multithreaded environment is only recommended
when required by other aspects of the application (for example, when writing a
Domino exit program or when calling a short-running RPG procedure from Java).
For long-running RPG programs called from Java, we recommend using a separate
process for the RPG program.
|
|
|
For a list of system functions that are not allowed or supported in a multithreaded
environment, refer to the Multithreaded Applications document under the Programming topic at the following URL:
|
http://www.as400.ibm.com/infocenter/
|
You cannot use the following in a thread-safe program:
|
¹ *INUx indicators
|
¹ External indicators (*INU1 - *INU8)
|
¹ The LR indicator for the CALL or CALLB operation
|
|
|
When using the THREAD(*SERIALIZE) keyword, remember the following:
¹ It is up to the programmer to ensure that storage that is shared across modules
is used in a thread-safe manner. This includes:
|
– Storage explicitly shared by being exported and imported.
|
|
– Storage shared because a procedure saves the address of a parameter or
a pointer parameter, or allocated storage, and uses it on a subsequent call.
|
|
¹ If shared files are used by more than one language (RPG and C, or RPG and
COBOL), ensure that only one language is accessing the file at one time.
TIMFMT(fmt{separator})
The TIMFMT keyword specifies the internal time format for time literals and the
default internal format for time fields within the program. You can specify a different
internal time format for a particular field by specifying the format with the TIMFMT
keyword on the definition specification for that field.
If the TIMFMT keyword is not specified the *ISO format is assumed. For more information on internal formats, see “Internal and External Formats” on page 159.
Table 16 on page 189 shows the time formats supported and their separators.
TRUNCNBR(*YES | *NO)
The TRUNCNBR keyword specifies if the truncated value is moved to the result
field or if an error is generated when numeric overflow occurs while running the
object.
Note: The TRUNCNBR option does not apply to calculations performed within
expressions. (Expressions are found in the Extended-Factor 2 field.) If overflow occurs for these calculations, an error will always occur.
Chapter 13. Control Specifications
247
Control-Specification Keywords
If *YES is specified, numeric overflow is ignored and the truncated value is moved
to the result field.
If *NO is specified, a run-time error is generated when numeric overflow is
detected.
If the TRUNCNBR keyword is not specified, then the value specified on the
command is used.
USRPRF(*USER | *OWNER)
The USRPRF keyword specifies the user profile that will run the created program
object. The profile of the program owner or the program user is used to run the
program and to control which objects can be used by the program (including the
authority the program has for each object). This keyword is not updated if the
program already exists.
If *USER is specified, the user profile of the program's user will run the created
program object.
If *OWNER is specified, the user profiles of both the program's user and owner will
run the created program object. The collective set of object authority in both user
profiles is used to find and access objects while the program is running. Any
objects created during the program are owned by the program's user.
If the USRPRF keyword is not specified, then the value specified on the command
is used.
The USRPRF keyword is valid only if the CRTBNDRPG command is used.
248
ILE RPG for AS/400 Reference
File Description Specification Statement
Chapter 14. File Description Specifications
File description specifications identify each file used by a program. Each file in a
program must have a corresponding file description specification statement.
A file can be either program-described or externally described. In programdescribed files, record and field descriptions are included within the RPG program
(using input and output specifications). Externally described files have their record
and field descriptions defined externally using DDS, DSU, IDDU, or SQL commands. (DSU is part of the CODE/400 product.)
The following limitations apply per program:
¹ Only one primary file can be specified. The presence of a primary file is not
required.
¹ Only one record-address file.
¹ A maximum of eight PRINTER files.
¹ There is no limit for the maximum number of files allowed.
File Description Specification Statement
The general layout for the file description specification is as follows:
¹ the file description specification type (F) is entered in position 6
¹ the non-commentary part of the specification extends from position 7 to position
80
– the fixed-format entries extend from positions 7 to 42
– the keyword entries extend from positions 44 to 80
¹ the comments section of the specification extends from position 81 to position
100
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords+++++++++++++++++++++++++++++Comments++++++++++++
Figure 101. File Description Specification Layout
File-Description Keyword Continuation Line
If additional space is required for keywords, the keywords field can be continued on
subsequent lines as follows:
¹ position 6 of the continuation line must contain an F
¹ positions 7 to 43 of the continuation line must be blank
¹ the specification continues on or past position 44
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
F.....................................Keywords+++++++++++++++++++++++++++++Comments++++++++++++
Figure 102. File-Description Keyword Continuation Line Layout
 Copyright IBM Corp. 1994, 1999
249
File Description Specification Statement
Position 6 (Form Type)
An F must be entered in this position for file description specifications.
Positions 7-16 (File Name)
Entry
Explanation
A valid file name
Every file used in a program must have a unique name. The file name
can be from 1 to 10 characters long, and must begin in position 7.
The file name specified in positions 7 through 16 must be an existing file name that
has been defined to the OS/400 system. However, one of the OS/400system override commands can be used to associate the RPG IV file name to the file name
defined to the OS/400 system.
For an externally described file, the file must exist at both compilation time and at
run time. For a program-described file, the file need exist only at run time.
When the files are opened at run time, they are opened in the reverse order to that
specified in the file description specifications. The RPG IV device name defines the
operations that can be processed on the associated file.
Program Described File
For program-described files, the file name entered in positions 7 through 16 must
also be entered on:
¹ Input specifications if the file is a primary, secondary, or full procedural file
¹ Output specifications or an output calculation operation line if the file is an
output, update, or combined file, or if file addition is specified for the file
¹ Definition specifications if the file is a table or array file.
¹ Calculation specifications if the file name is required for the operation code
specified
Externally Described File
For externally described files, the file name entered in positions 7 through 16 is the
name used to locate the record descriptions for the file. The following rules apply
to externally described files:
¹ Input and output specifications for externally described files are optional. They
are required only if you are adding RPG IV functions, such as control fields or
record identifying indicators, to the external description retrieved.
¹ When an external description is retrieved, the record definition can be referred
to by its record format name on the input, output, or calculation specifications.
¹ A record format name must be a unique symbolic name.
¹ RPG IV does not support an externally described logical file with two record
formats of the same name. However, such a file can be accessed if it is
program described.
250
ILE RPG for AS/400 Reference
File Description Specification Statement
Position 17 (File Type)
Entry
Explanation
I
Input file
O
Output file
U
Update file
C
Combined (input/output) file.
Input Files
An input file is one from which a program reads information. It can contain data
records, arrays, or tables, or it can be a record-address file.
Output Files
An output file is a file to which information is written.
Update Files
An update file is an input file whose records can be read and updated. Updating
alters the data in one or more fields of any record contained in the file and writes
that record back to the same file from which it was read. If records are to be
deleted, the file must be specified as an update file.
Combined Files
A combined file is both an input file and an output file. When a combined file is
processed, the output record contains only the data represented by the fields in the
output record. This differs from an update file, where the output record contains the
input record modified by the fields in the output record.
A combined file is valid for a SPECIAL or WORKSTN file. A combined file is also
valid for a DISK or SEQ file if position 18 contains T (an array or table replacement
file).
Position 18 (File Designation)
Entry
Explanation
Blank
Output file
P
Primary file
S
Secondary file
R
Record address file
T
Array or table file
F
Full procedural file
You cannot specify P, S, or R if the keyword NOMAIN is specified on a control
specification.
Chapter 14. File Description Specifications
251
File Description Specification Statement
Primary File
When several files are processed by cycle processing, one must be designated as
the primary file. In multi-file processing, processing of the primary file takes precedence. Only one primary file is allowed per program.
Secondary File
When more than one file is processed by the RPG cycle, the additional files are
specified as secondary files. Secondary files must be input capable (input, update,
or combined file type). The processing of secondary files is determined by the order
in which they are specified in the file description specifications and by the rules of
multi-file logic.
Record Address File (RAF)
A record-address file is a sequentially organized file used to select records from
another file. Only one file in a program can be specified as a record-address file.
This file is described on the file description specification and not on the input specifications. A record-address file must be program-described; however, a recordaddress file can be used to process a program described file or an externally
described file.
The file processed by the record-address file must be a primary, secondary, or fullprocedural file, and must also be specified as the parameter to the RAFDATA
keyword on the file description specification of the record-address file.
You cannot specify a record-address file for the device SPECIAL.
|
UCS-2 fields are not allowed as the record address type for record address files.
A record-address file that contains relative-record numbers must also have a T
specified in position 35 and an F in position 22.
Array or Table File
Array and table files specified by a T in position 18 are loaded at program initialization time. The array or table file can be input or combined. Leave this entry blank
for array or table output files. You cannot specify SPECIAL as the device for array
and table input files. You cannot specify an externally described file as an array or
table file.
If T is specified in position 18, you can specify a file type of combined (C in position
17) for a DISK or SEQ file. A file type of combined allows an array or table file to
be read from or written to the same file (an array or table replacement file). In addition to a C in position 17, the filename in positions 7-16 must also be specified as
the parameter to the TOFILE keyword on the definition specification.
Full Procedural File
A full procedural file is not processed by the RPG cycle: input is controlled by calculation operations. File operation codes such as CHAIN or READ are used to do
input functions.
252
ILE RPG for AS/400 Reference
File Description Specification Statement
Position 19 (End of File)
Entry
Explanation
E
All records from the file must be processed before the program can end.
This entry is not valid for files processed by a record-address file.
All records from all files which use this option must be processed before
the LR indicator is set on by the RPG cycle to end the program.
Blank
If position 19 is blank for all files, all records from all files must be processed before end of program (LR) can occur. If position 19 is not blank
for all files, all records from this file may or may not be processed before
end of program occurs in multi-file processing.
Use position 19 to indicate whether the program can end before all records from
the file are processed. An E in position 19 applies only to input, update, or combined files specified as primary, secondary, or record-address files.
If the records from all primary and secondary files must be processed, position 19
must be blank for all files or must contain E's for all files. For multiple input files,
the end-of-program (LR) condition occurs when all input files for which an E is
specified in position 19 have been processed. If position 19 is blank for all files, the
end-of-program condition occurs when all input files have been processed.
When match fields are specified for two or more files and an E is specified in position 19 for one or more files, the LR indicator is set on after:
¹ The end-of-file condition occurs for the last file with an E specified in position
19.
¹ The program has processed all the records in other files that match the last
record processed from the primary file.
¹ The program has processed the records in those files without match fields up
to the next record with non-matching match fields.
When no file or only one file contains match field specifications, no records of other
files are processed after end of file occurs on all files for which an E is specified in
position 19.
Position 20 (File Addition)
Position 20 indicates whether records are to be added to an input or update file.
For output files, this entry is ignored.
Entry
Explanation
Blank
No records can be added to an input or update file (I or U in position
17).
A
Records are added to an input or update file when positions 18 through
20 of the output record specifications for the file contain "ADD", or when
the WRITE operation code is used in the calculation specification.
See Table 25 on page 254 for the relationship between position 17 and position 20
of the file description specifications and positions 18 through 20 of the output specifications.
Chapter 14. File Description Specifications
253
File Description Specification Statement
Table 25. Processing Functions for Files
Specification
File Description
Output
Function
Position 17
Position 20
Positions 18-20
Create new file1
or
Add records to existing file
O
O
Blank
A
Blank
ADD
Process file
I
Blank
Blank
Process file and add records to the
existing file
I
A
ADD
Process file and update the records
(update or delete)
U
Blank
Blank
Process file and add new records to an
existing file
U
A
ADD
Process file and delete an existing record
from the file
U
Blank
DEL
Note: Within RPG, the term create a new file means to add records to a newly created file. Thus, the first two
entries in this table perform the identical function. Both are listed to show that there are two ways to
specify that function.
Position 21 (Sequence)
Entry
Explanation
A or blank
Match fields are in ascending sequence.
D
Match fields are in descending sequence.
Position 21 specifies the sequence of input fields used with the match fields specification (positions 65 and 66 of the input specifications). Position 21 applies only to
input, update, or combined files used as primary or secondary files. Use positions
65 and 66 of the input specifications to identify the fields containing the sequence
information.
If more than one input file with match fields is specified in the program, a sequence
entry in position 21 can be used to check the sequence of the match fields and to
process the file using the matching record technique. The sequence need only be
specified for the first file with match fields specified. If sequence is specified for
other files, the sequence specified must be the same; otherwise, the sequence
specified for the first file is assumed.
If only one input file with match fields is specified in the program, a sequence entry
in position 21 can be used to check fields of that file to ensure that the file is in
sequence. By entering one of the codes M1 through M9 in positions 65 and 66 of
the input specifications, and by entering an A, blank, or D in position 21, you
specify sequence checking of these fields.
Sequence checking is required when match fields are used in the records from the
file. When a record from a matching input file is found to be out of sequence, the
RPG IV exception/error handling routine is given control.
254
ILE RPG for AS/400 Reference
File Description Specification Statement
Position 22 (File Format)
Entry
Explanation
F
Program-described file
E
Externally described file
An F in position 22 indicates that the records for the file are described within the
program on input/output specifications (except for array/table files and recordaddress files).
An E in position 22 indicates that the record descriptions for the file are external to
the RPG IV source program. The compiler obtains these descriptions at compilation
time and includes them in the source program.
Positions 23-27 (Record Length)
Use positions 23 through 27 to indicate the length of the logical records contained
in a program-described file. The maximum record size that can be specified is
32766; however, record-size constraints of any device may override this value. This
entry must be blank for externally described files.
If the file being defined is a record-address file and the record length specified is 3,
it is assumed that each record in the file consists of a 3-byte binary field for the
relative-record numbers starting at offset 0. If the record length is 4 or greater, each
relative-record number in the record-address file is assumed to be a 4-byte field
starting at offset 1. If the record length is left blank, the actual record length is
retrieved at run time to determine how to handle the record-address file.
If the file opened at run time has a primary record length of 3, then 3-byte relativerecord numbers (one per record) are assumed; otherwise, 4-byte relative-record
numbers are assumed. This support can be used to allow ILE RPG programs to
use System/36 environment SORT files as record-address files.
Table 26. Valid Combinations for a Record Address File containing Relative Record
Numbers (RAFRRN)
Record Length
Positions 23-27
RAF Length
Positions 29-33
Type of Support
Blank
Blank
Support determined at run time.
3
3
System/36 support.
>=4
4
Native support.
Position 28 (Limits Processing)
Entry
Explanation
L
Sequential-within-limits processing by a record-address file
Blank
Sequential or random processing
Use position 28 to indicate whether the file is processed by a record-address file
that contains limits records.
A record-address file used for limits processing contains records that consist of
upper and lower limits. Each record contains a set of limits that consists of the
Chapter 14. File Description Specifications
255
File Description Specification Statement
lowest record key and the highest record key from the segment of the file to be
processed. Limits processing can be used for keyed files specified as primary, secondary, or full procedural files.
The L entry in position 28 is valid only if the file is processed by a record-address
file containing limits records. Random and sequential processing of files is implied
by a combination of positions 18 and 34 of the file description specifications, and by
the calculation operation specified.
The operation codes “SETLL (Set Lower Limit)” on page 650 and “SETGT (Set
Greater Than)” on page 646 can be used to position a file; however, the use of
these operation codes does not require an L in this position.
For more information on limits processing, refer to the ILE RPG for AS/400 Programmer's Guide .
Positions 29-33 (Length of Key or Record Address)
Entry
Explanation
1-2000
The number of positions required for the key field in a program
described file or the length of the entries in the record-address file
(which must be a program-described file).
If the program-described file being defined uses keys for record identification, enter the number of positions occupied by each record key. This
entry is required for indexed files.
If the keys are packed, the key field length should be the packed length;
this is the number of digits in DDS divided by 2 plus 1 and ignoring any
fractions.
If the file being defined is a record-address file, enter the number of
positions that each entry in the record-address file occupies.
If the keys are graphic, the key field length should be specified in bytes
(for example, 3 graphic characters requires 6 bytes).
Blank
These positions must be blank for externally described files. (The key
length is specified in the external description.) For a program-described
file, a blank entry indicates that keys are not used. Positions 29-33 can
also be blank for a record-address file with a blank in positions 23-27
(record length).
Position 34 (Record Address Type)
Entry
Explanation
Blank
Relative record numbers are used to process the file.
Records are read consecutively.
Record address file contains relative-record numbers.
For limits processing, the record-address type (position 34) is the same
as the type of the file being processed.
A
256
ILE RPG for AS/400 Reference
Character keys (valid only for program-described files specified as
indexed files or as a record-address-limits file).
File Description Specification Statement
|
|
P
Packed keys (valid only for program-described files specified as indexed
files or as a record-address-limits file).
G
Graphic keys (valid only for program-described files specified as indexed
files or as a record-address-limits file).
K
Key values are used to process the file. This entry is valid only for
externally described files.
D
Date keys are used to process the file. This entry is valid only for
program-described files specified as indexed files or as a recordaddress-limits file.
T
Time keys are used to process the file. This entry is valid only for
program-described files specified as indexed files or as a recordaddress-limits file.
Z
Timestamp Keys are used to process the file. This entry is valid only for
program-described files specified as indexed files or as a recordaddress-limits file.
F
Float Key (valid only for program-described files specified as indexed
files or as a record-address-limits file).
UCS-2 fields are not allowed as the record address type for program described
indexed files or record address files.
Blank=Non-keyed Processing
A blank indicates that the file is processed without the use of keys, that the recordaddress file contains relative-record numbers (a T in position 35), or that the keys
in a record-address-limits file are in the same format as the keys in the file being
processed.
A file processed without keys can be processed consecutively or randomly by
relative-record number.
Input processing by relative-record number is determined by a blank in position 34
and by the use of the CHAIN, SETLL, or SETGT operation code. Output processing by relative-record number is determined by a blank in position 34 and by the
use of the RECNO keyword on the file description specifications.
A=Character Keys
The indexed file (I in position 35) defined on this line is processed by characterrecord keys. (A numeric field used as the search argument is converted to zoned
decimal before chaining.) The A entry must agree with the data format of the field
identified as the key field (length in positions 29 to 33 and starting position specified
as the parameter to the KEYLOC keyword).
The record-address-limits file (R in position 18) defined on this line contains character keys. The file being processed by this record address file can have an A, P,
or K in position 34.
Chapter 14. File Description Specifications
257
File Description Specification Statement
P=Packed Keys
The indexed file (I in position 35) defined on this line is processed by packeddecimal-numeric keys. The P entry must agree with the data format of the field
identified as the key field (length in positions 29 to 33 and starting position specified
as the parameter to the KEYLOC keyword).
The record-address-limits file defined on this line contains record keys in packed
decimal format. The file being processed by this record address file can have an A,
P, or K in position 34.
G=Graphic Keys
The indexed file (I in position 35) defined on this line is processed by graphic keys.
Since each graphic character requires two bytes, the key length must be an even
number. The record-address file which is used to process this indexed file must
also have a 'G' specified in position 34 of its file description specification, and its
key length must also be the same as the indexed file's key length (positions 29-33).
K=Key
A K entry indicates that the externally described file is processed on the assumption that the access path is built on key values. If the processing is random, key
values are used to identify the records.
If this position is blank for a keyed file, the records are retrieved in arrival
sequence.
D=Date Keys
The indexed file (I in position 35) defined on this line is processed by date keys.
The D entry must agree with the data format of the field identified as the key field
(length in positions 29 to 33 and starting position specified as the parameter to the
KEYLOC keyword).
The hierarchy used when determining the format and separator for the date key is:
1. From the DATFMT keyword specified on the file description specification
2. From the DATFMT keyword specified in the control specification
3. *ISO
T=Time Keys
The indexed file (I in position 35) defined on this line is processed by time keys.
The T entry must agree with the data format of the field identified as the key field
(length in positions 29 to 33 and starting position specified as the parameter to the
KEYLOC keyword).
The hierarchy used when determining the format and separator for the time key is:
1. From the TIMFMT keyword specified on the file description specification
2. From the TIMFMT keyword specified in the control specification
3. *ISO
258
ILE RPG for AS/400 Reference
File Description Specification Statement
Z=Timestamp Keys
The indexed file (I in position 35) defined on this line is processed by timestamp
keys. The Z entry must agree with the data format of the field identified as the key
field (length in positions 29 to 33 and starting position specified as the parameter to
the KEYLOC keyword).
F=Float Keys
The indexed file (I in position 35) defined on this line is processed by float keys.
The Length-of-Key entry (positions 29-33) must contain a value of either 4 or 8 for
a float key. When a file contains a float key, any type of numeric variable or literal
may be specified as a key on keyed input/output operations. For a non-float record
address type, you cannot have a float search argument.
For more information on record address type, refer to the ILE RPG for AS/400 Programmer's Guide.
Position 35 (File Organization)
Entry
Explanation
Blank
The program-described file is processed without keys, or the file is
externally described.
I
Indexed file (valid only for program-described files).
T
Record address file that contains relative-record numbers (valid only for
program-described files).
Use position 35 to identify the organization of program described files.
Blank=Non-keyed Program-Described File
A program-described file that is processed without keys can be processed:
¹ Randomly by relative-record numbers, positions 28 and 34 must be blank.
¹ Entry Sequence, positions 28 and 34 must be blank.
¹ As a record-address file, position 28 must be blank.
I=Indexed File
An indexed file can be processed:
¹ Randomly or sequentially by key
¹ By a record-address file (sequentially within limits). Position 28 must contain an
L.
T=Record Address File
A record-address file (indicated by an R in position 18) that contains relative-record
numbers must be identified by a T in position 35. (A record-address file must be
program described.) Each record retrieved from the file being processed is based
on the relative record number in the record-address file. (Relative record numbers
cannot be used for a record-address-limits file.)
Each relative-record number in the record-address file is a 4-byte binary field;
therefore, each 4-byte unit of a record-address file contains a relative-record
number. A minus one (-1 or hexadecimal FFFFFFFF ) relative-record number value
Chapter 14. File Description Specifications
259
File-Description Keywords
causes the record to be skipped. End of file occurs when all record-address file
records have been processed.
For more information on how to handle record-address files, see the ILE RPG for
AS/400 Programmer's Guide.
Positions 36-42 (Device)
Entry
Explanation
PRINTER File is a printer file, a file with control characters that can be sent to a
printer.
DISK
File is a disk file. This device supports sequential and random read/write
functions. These files can be accessed on a remote system by Distributed Data Management (DDM).
WORKSTN
File is a workstation file. Input/output is through a display or ICF file.
SPECIAL This is a special file. Input or output is on a device that is accessed by a
user-supplied program. The name of the program must be specified as
the parameter for the PGMNAME keyword. A parameter list is created
for use with this program, including an option code parameter and a
status code parameter. The file must be a fixed unblocked format. See
“PLIST(Plist_name)” on page 267 and “PGMNAME(program_name)” on
page 266 for more information.
SEQ
File is a sequentially organized file. The actual device is specified in a
CL command or in the file description, which is accessed by the file
name.
Use positions 36 through 42 to specify the RPG IV device name to be associated
with the file. The RPG IV device name defines the ILE RPG functions that can be
done on the associated file. Certain functions are valid only for a specific ILE RPG
device name (such as the EXFMT operation for WORKSTN). The file name specified in positions 7 through 16 can be overridden at run time, allowing you to change
the input/output device used in the program.
Note that the RPG IV device names are not the same as the system device names.
Position 43 (Reserved)
Position 43 must be blank.
Positions 44-80 (Keywords)
Positions 44 to 80 are provided for file-description-specification keywords.
Keywords are used to provide additional information about the file being defined.
File-Description Keywords
File-Description keywords may have no parameters, optional parameters, or
required parameters. The syntax for keywords is as follows:
Keyword(parameter1 : parameter2)
where:
260
ILE RPG for AS/400 Reference
File-Description Keywords
¹ Parameter(s) are enclosed in parentheses ( ).
Note: Do not specify parentheses if there are no parameters.
¹ Colons (:) are used to separate multiple parameters.
The following notational conventions are used to show which parameters are
optional and which are required:
¹ Braces { } indicate optional parameters or optional elements of parameters.
¹ An ellipsis (...) indicates that the parameter can be repeated.
¹ A colon (:) separates parameters and indicates that more than one may be
specified. All parameters separated by a colon are required unless they are
enclosed in braces.
¹ A vertical bar (|) indicates that only one parameter may be specified for the
keyword.
¹ A blank separating keyword parameters indicates that one or more of the
parameters may be specified.
Note: Braces, ellipses, and vertical bars are not a part of the keyword syntax and
should not be entered into your source.
If additional space is required for file-description keywords, the keyword field can be
continued on subsequent lines. See “File-Description Keyword Continuation Line”
on page 249 and “File Description Specification Keyword Field” on page 228.
BLOCK(*YES |*NO)
The BLOCK keyword controls the blocking of records associated with the file. The
keyword is valid only for DISK or SEQ files.
If this keyword is not specified, the RPG compiler unblocks input records and
blocks output records to improve run-time performance in SEQ or DISK files when
the following conditions are met:
1. The file is program-described or, if externally described, it has only one record
format.
2. Keyword RECNO is not used in the file description specification.
Note: If RECNO is used, the ILE RPG compiler will not allow record blocking.
However, if the file is an input file and RECNO is used, Data Management may still block records if fast sequential access is set. This means
that updated records might not be seen right away.
3. One of the following is true:
a. The file is an output file.
b. If the file is a combined file, then it is an array or table file.
c. The file is an input-only file; it is not a record-address file or processed by a
record-address file; and none of the following operations are used on the
file: READE, READPE, SETGT, SETLL, and CHAIN. (If any READE or
READPE operations are used, no record blocking will occur for the input
file. If any SETGT, SETLL, or CHAIN operations are used, no record
blocking will occur unless the BLOCK(*YES) keyword is specified for the
input file.)
Chapter 14. File Description Specifications
261
File-Description Keywords
If BLOCK(*YES) is specified, record blocking occurs as described above except
that the operations SETLL, SETGT, and CHAIN can be used with an input file and
blocking will still occur (see condition 3c above). To prevent the blocking of records,
BLOCK(*NO) can be specified. Then no record blocking is done by the compiler.
COMMIT{(rpg_name)}
The COMMIT keyword allows the processing files under commitment control. An
optional parameter, rpg_name, may be specified. The parameter is implicitly
defined as a field of type indicator (that is, a character field of length one), and is
initialized by RPG to '0'.
By specifying the optional parameter, you can control at run time whether to enable
commitment control. If the parameter contains a '1', the file will be opened with the
COMMIT indication on, otherwise the file will be opened without COMMIT. The
parameter must be set prior to opening the file. If the file is opened at program
initialization, the COMMIT parameter can be passed as a call parameter or defined
as an external indicator. If the file is opened explicitly, using the OPEN operation in
the calculation specifications, the parameter can be set prior to the OPEN operation.
Use the COMMIT and ROLBK operation codes to group changes to this file and
other files currently under commitment control so that changes all happen together,
or do not happen at all.
Note: If the file is already open with a shared open data path, the value for commitment control must match the value for the previous OPEN operation.
DATFMT(format{separator})
The DATFMT keyword allows the specification of a default external date format and
a default separator (which is optional) for all date fields in the program-described
file. If the file on which this keyword is specified is indexed and the key field is a
date, then this also provides the default external format for the key field.
For a Record-Address file this specifies the external date format of date limits keys
read from the record-address file.
You can specify a different external format for individual input or output date fields
in the file by specifying a date format/separator for the field on the corresponding
input specification (positions 31-35) or output specification (positions 53-57).
See Table 13 on page 186 for valid formats and separators. For more information
on external formats, see “Internal and External Formats” on page 159.
DEVID(fieldname)
The DEVID keyword specifies the name of the program device that supplied the
record processed in the file. The field is updated each time a record is read from a
file. Also, you may move a program device name into this field to direct an output
or device-specific input operation (other than a READ-by-file-name or an implicit
cycle read) to a different device.
The fieldname is implicitly defined as a 10-character alphanumeric field. The
device name specified in the field must be left-justified and padded with blanks.
262
ILE RPG for AS/400 Reference
File-Description Keywords
Initially, the field is blank. A blank field indicates the requester device. If the
requester device is not acquired for your file, you must not use a blank field.
The DEVID field is maintained for each call to a program. If you call program B
from within program A, the DEVID field for program A is not affected. Program B
uses a separate DEVID field. When you return to program A, its DEVID field has
the same value as it had before you called program B. If program B needs to know
which devices are acquired to program A, program A must pass this information (as
a parameter list) when it calls program B.
If the DEVID keyword is specified but not the MAXDEV keyword, the program
assumes a multiple device file (MAXDEV with a parameter of *FILE).
To determine the name of the requester device, you may look in the appropriate
area of the file information data structure (see “File Information Data Structure” on
page 65). Or, you may process an input or output operation where the fieldname
contains blanks. After the operation, the fieldname has the name of the requester
device.
EXTIND(*INUx)
The EXTIND keyword indicates whether the file is used in the program depending
on the value of the external indicator.
EXTIND lets the programmer control the operation of input, output, update, and
combined files at run time. If the specified indicator is on at program initialization,
the file is opened. If the indicator is not on, the file is not opened and is ignored
during processing. The *INU1 through *INU8 indicators can be set as follows:
¹ By the OS/400 control language.
¹ When used as a resulting indicator for a calculation operation or as field indicators on the input specifications. Setting the *INU1 through *INU8 indicators in
this manner has no effect on file conditioning.
See also “USROPN” on page 271.
FORMLEN(number)
The FORMLEN keyword specifies the form length of a PRINTER file. The form
length must be greater than or equal to 1 and less than or equal to 255. The
parameter specifies the exact number of lines available on the form or page to be
used.
Changing the form length does not require recompiling the program. You can override the number parameter of FORMLEN by specifying a new value for the
PAGSIZE parameter of the Override With Printer File (OVRPRTF) command.
When the FORMLEN keyword is specified, the FORMOFL keyword must also be
specified.
Chapter 14. File Description Specifications
263
File-Description Keywords
FORMOFL(number)
The FORMOFL keyword specifies the overflow line number that will set on the
overflow indicator. The overflow line number must be less than or equal to the form
length. When the line that is specified as the overflow line is printed, the overflow
indicator is set on.
Changing the overflow line does not require recompiling the program. You can
override the number parameter of FORMOFL by specifying a new value for the
OVRFLW parameter of the Override With Printer File (OVRPRTF) command.
When the FORMOFL keyword is specified, the FORMLEN keyword must also be
specified.
IGNORE(recformat{:recformat...})
The IGNORE keyword allows a record format from an externally described file to be
ignored. The external name of the record format to be ignored is specified as the
parameter recformat. One or more record formats can be specified, separated by
colons (:). The program runs as if the specified record format(s) did not exist. All
other record formats contained in the file will be included.
When the IGNORE keyword is specified for a file, the INCLUDE keyword cannot be
specified.
INCLUDE(recformat{:recformat...})
The INCLUDE keyword specifies those record format names that are to be
included; all other record formats contained in the file will be ignored. For
WORKSTN files, the record formats specified using the SFILE keyword are also
included in the program, they need not be specified twice. Multiple record formats
can be specified, separated by colons (:).
When the INCLUDE keyword is specified for a file, the IGNORE keyword cannot be
specified.
INDDS(data_structure_name)
The INDDS keyword lets you associate a data structure name with the INDARA
indicators for a workstation or printer file. This data structure contains the conditioning and response indicators passed to and from data management for the file,
and is called an indicator data structure.
Rules:
¹ This keyword is allowed only for externally described PRINTER files and
externally and program-described WORKSTN files.
¹ For a program-described file, the PASS(*NOIND) keyword must not be specified with the INDDS keyword.
¹ The same data structure name may be associated with more than one file.
¹ The data structure name must be defined as a data structure on the definition
specifications and can be a multiple-occurrence data structure.
¹ The length of the indicator data structure is always 99.
¹ The indicator data structure is initialized by default to all zeros ('0's).
264
ILE RPG for AS/400 Reference
File-Description Keywords
¹ The SAVEIND keyword cannot be specified with this keyword.
If this keyword is not specified, the *IN array is used to communicate indicator
values for all files defined with the DDS keyword INDARA.
For additional information on indicator data structures, see “Special Data
Structures” on page 126.
INFDS(DSname)
The INFDS keyword lets you define and name a data structure to contain the feedback information associated with the file. The data structure name is specified as
the parameter for INFDS. If INFDS is specified for more than one file, each associated data structure must have a unique name. An INFDS can only be defined in the
main source section.
For additional information on file information data structures, see “File Information
Data Structure” on page 65.
INFSR(SUBRname)
The INFSR keyword identifies the file exception/error subroutine that may receive
control following file exception/errors. The subroutine name may be *PSSR, which
indicates the user-defined program exception/error subroutine is to be given control
for errors on this file.
The INFSR keyword cannot be specified if the file is to be accessed by a subprocedure, or if NOMAIN is specified on the control specification.
KEYLOC(number)
The KEYLOC keyword specifies the record position in which the key field for a
program-described indexed-file begins. The parameter must be between 1 and
32766.
The key field of a record contains the information that identifies the record. The key
field must be in the same location in all records in the file.
MAXDEV(*ONLY | *FILE)
The MAXDEV keyword specifies the maximum number of devices defined for the
WORKSTN file. The default, *ONLY, indicates a single device file. If *FILE is specified, the maximum number of devices (defined for the WORKSTN file on the
create-file command) is retrieved at file open, and SAVEIND and SAVEDS space
allocation will be done at run time.
With a shared file, the MAXDEV value is not used to restrict the number of
acquired devices.
When you specify DEVID, SAVEIND, or SAVEDS but not MAXDEV, the program
assumes the default of a multiple device file (MAXDEV with a parameter of *FILE).
Chapter 14. File Description Specifications
265
File-Description Keywords
OFLIND(*INxx)
The OFLIND keyword specifies an overflow indicator to condition which lines in the
PRINTER file will be printed when overflow occurs. This entry is valid only for a
PRINTER device. Default overflow processing (that is, automatic page eject at
overflow) is done if the OFLIND keyword is not specified.
Valid Parameters:
*INOA-*INOG, *INOV:
Specified overflow indicator conditions the lines to be printed when overflow occurs on a program described printer file.
*IN01-*IN99:
Set on when a line is printed on the overflow line, or the overflow line is
reached or passed during a space or skip operation.
Note: Indicators *INOA through *INOG, and *INOV are not valid for externally
described files.
Only one overflow indicator can be assigned to a file. If more than one PRINTER
file in a program is assigned an overflow indicator, that indicator must be unique for
each file.
PASS(*NOIND)
The PASS keyword determines whether indicators are passed under programmer
control or based on the DDS keyword INDARA. This keyword can only be specified
for program-described files. To indicate that you are taking responsibility for passing
indicators on input and output, specify PASS(*NOIND) on the file description specification of the corresponding program-described WORKSTN file.
When PASS(*NOIND) is specified, the ILE RPG compiler does not pass indicators
to data management on output, nor does it receive them on input. Instead you
pass indicators by describing them as fields (in the form *INxx, *IN(xx), or *IN) in
the input or output record. They must be specified in the sequence required by the
data description specifications (DDS). You can use the DDS listing to determine
this sequence.
If this keyword is not specified, the compiler assumes that INDARA was specified in
the DDS.
Note: If the file has the INDARA keyword specified in the DDS, you must not
specify PASS(*NOIND). If it does not, you must specify PASS(*NOIND).
PGMNAME(program_name)
The PGMNAME keyword identifies the program that is to handle the support for the
special I/O device (indicated by a Device-Entry of SPECIAL).
Note: The parameter must be a valid program name and not a bound procedure
name.
See “Positions 36-42 (Device)” on page 260 and “PLIST(Plist_name)” on page 267
for more information.
266
ILE RPG for AS/400 Reference
File-Description Keywords
PLIST(Plist_name)
The PLIST keyword identifies the name of the parameter list to be passed to the
program for the SPECIAL file. The parameters identified by this entry are added to
the end of the parameter list passed by the program. (The program is specified
using the PGMNAME keyword, see “PGMNAME(program_name)” on page 266.)
This keyword can only be specified when the Device-Entry (positions 36 to 42) in
the file description line is SPECIAL.
PREFIX(prefix_string{:nbr_of_char_replaced})
The PREFIX keyword is used to partially rename the fields in an externally
described file. The characters specified as 'prefix_string' are prefixed to the names
of all fields defined in all records of the file specified in positions 7-16. In addition,
you can optionally specify a numeric value to indicate the number of characters, if
any, in the existing name to be replaced. If the 'nbr_of_char_replaced' is not specified, then the string is attached to the beginning of the name.
If the 'nbr_of_char_replaced' is specified, it must be a numeric constant containing
a value between 0 and 9 with no decimal places. For example, the specification
PREFIX(YE:3) would change the field name 'YTDTOTAL' to 'YETOTAL'. Specifying
a value of zero is the same as not specifying 'nbr_of_char_replaced' at all.
Rules:
¹ You can explicitly rename a field on an input specification, even when the
PREFIX keyword is specified for a file. The compiler will recognize (and
require) the name which is first USED in your program. For example, if you
specify the prefixed name on an input specification to associate the field with
an indicator, and you then try to rename the field referencing the unprefixed
name, you will get an error. Conversely, if you first rename the field to something other than the prefixed name, and you then use the prefixed name on a
specification, you will get an error at compile-time.
¹ The total length of the name after applying the prefix must not exceed the
maximum length of an RPG field name.
¹ If the number of characters in the name to be prefixed is less
¹ The number of characters in the name to be prefixed must not be less than or
equal to the value represented by the 'nbr_of_char_replaced' parameter. That
is, after applying the prefix, the resulting name must not be the same as the
prefix string.
PRTCTL(data_struct{:*COMPAT})
The PRTCTL keyword specifies the use of dynamic printer control. The data structure specified as the parameter data_struct refers to the forms control information
and line count value. The PRTCTL keyword is valid only for a program described
file.
The optional parameter *COMPAT indicates that the data structure layout is compatible with RPG III. The default, *COMPAT not specified, will require the use of the
extended length data structure.
Chapter 14. File Description Specifications
267
File-Description Keywords
Extended Length PRTCTL Data Structure
A minimum of 15 bytes is required for this data structure. Layout of the PRTCTL
data structure is as follows:
Data Structure Positions Subfield Contents
1-3
A three-position character field that contains the space-before value
(valid entries: blank or 0-255)
4-6
A three-position character field that contains the space-after value (valid
entries: blank or 0-255)
7-9
A three-position character field that contains the skip-before value (valid
entries: blank or 1-255)
10-12
A three-position character field that contains the skip-after value (valid
entries: blank or 1-255)
13-15
A three-digit numeric (zoned decimal) field with zero decimal positions
that contains the current line count value.
*COMPAT PRTCTL Data Structure
Data Structure Positions Subfield Contents
1
A one-position character field that contains the space-before value (valid
entries: blank or 0-3)
2
A one-position character field that contains the space-after value (valid
entries: blank or 0-3)
3-4
A two-position character field that contains the skip-before value (valid
entries: blank, 1-99, A0-A9 for 100-109, B0-B2 for 110-112)
5-6
A two-position character field that contains the skip-after value (valid
entries: blank, 1-99, A0-A9 for 100-109, B0-B2 for 110-112)
7-9
A three-digit numeric (zoned decimal) field with zero decimal positions
that contains the current line count value.
The values contained in the first four subfields of the extended length data structure
are the same as those allowed in positions 40 through 51 (space and skip entries)
of the output specifications. If the space and skip entries (positions 40 through 51)
of the output specifications are blank, and if subfields 1 through 4 are also blank,
the default is to space 1 after. If the PRTCTL option is specified, it is used only for
the output records that have blanks in positions 40 through 51. You can control the
space and skip value (subfields 1 through 4) for the PRINTER file by changing the
values in these subfields while the program is running.
Subfield 5 contains the current line count value. The ILE RPG compiler does not
initialize subfield 5 until after the first output line is printed. The compiler then
changes subfield 5 after each output operation to the file.
RAFDATA(filename)
The RAFDATA keyword identifies the name of the input or update file that contains
the data records to be processed for a Record Address File (RAF) (an R in position
18). See “Record Address File (RAF)” on page 252 for further information.
268
ILE RPG for AS/400 Reference
File-Description Keywords
RECNO(fieldname)
The RECNO keyword specifies that a DISK file is to be processed by relativerecord number. The RECNO keyword must be specified for output files processed
by relative-record number, output files that are referenced by a random WRITE calculation operation, or output files that are used with ADD on the output specifications.
The RECNO keyword can be specified for input/update files. The relative-record
number of the record retrieved is placed in the 'fieldname', for all operations that
reposition the file (such as READ, SETLL, or OPEN). It must be defined as numeric
with zero decimal positions. The field length must be sufficient to contain the
longest record number for the file.
The compiler will not open a SEQ or DISK file for blocking or unblocking records if
the RECNO keyword is specified for the file. Note that the keywords RECNO and
BLOCK(*YES) cannot be specified for the same file.
Note: When the RECNO keyword is specified for input or update files with fileaddition ('A' in position 20), the value of the fieldname parameter must refer
to a relative-record number of a deleted record, for the output operation to
be successful.
RENAME(Ext_format:Int_format)
The RENAME keyword allows you to rename record formats in an externally
described file. The external name of the record format that is to be renamed is
entered as the Ext_format parameter. The Int_format parameter is the name of the
record as it is used in the program. The external name is replaced by this name in
the program.
To rename all fields by adding a prefix, use the PREFIX keyword.
SAVEDS(DSname)
The SAVEDS keyword allows the specification of the data structure saved and
restored for each device. Before an input operation, the data structure for the
device operation is saved. After the input operation, the data structure for the
device associated with this current input operation is restored. This data structure
cannot be a data area data structure, file information data structure, or program
status data structure, and it cannot contain a compile-time array or prerun-time
array.
If the SAVEDS keyword is not specified, no saving and restoring is done. SAVEDS
must not be specified for shared files.
When you specify SAVEDS but not MAXDEV, the ILE RPG program assumes a
multiple device file (MAXDEV with a parameter of *FILE).
SAVEIND(number)
The SAVEIND keyword specifies the number of indicators that are to be saved and
restored for each device attached to a mixed or multiple device file. Before an
input operation, the indicators for the device associated with the previous input or
output operation are saved. After the input operation, the indicators for the device
associated with this current input operation are restored.
Chapter 14. File Description Specifications
269
File-Description Keywords
Specify a number from 1 through 99, as the parameter to the SAVEIND keyword.
No indicators are saved and restored if the SAVEIND keyword is not specified, or if
the MAXDEV keyword is not specified or specified with the parameter *ONLY.
If you specified the DDS keyword INDARA, the number you specify for the
SAVEIND keyword must be less than any response indicator you use in your DDS.
For example, if you specify INDARA and CF01(55) in your DDS, the maximum
value for the SAVEIND keyword is 54. The SAVEIND keyword must not be used
with shared files.
The INDDS keyword cannot be specified with this keyword.
When you specify the SAVEIND keyword but not the MAXDEV keyword, the ILE
RPGprogram assumes a multiple device file.
SFILE(recformat:rrnfield)
The SFILE keyword is used to define internally the subfiles that are specified in an
externally described WORKSTN file. The recformat parameter identifies the RPG IV
name of the record format to be processed as a subfile. The rrnfield parameter
identifies the name of the relative-record number field for this subfile. You must
specify an SFILE keyword for each subfile in the DDS.
The relative-record number of any record retrieved by a READC or CHAIN operation is placed into the field identified by the rrnfield parameter. This field is also
used to specify the record number that RPG IV uses for a WRITE operation to the
subfile or for output operations that use ADD. The field name specified as the
rrnfield parameter must be defined as numeric with zero decimal positions. The
field must have enough positions to contain the largest record number for the file.
(See the SFLSIZ keyword in the DDS Reference.)
Relative record number processing is implicitly defined as part of the SFILE definition. If multiple subfiles are defined, each subfile requires the specification of the
SFILE keyword.
Do not use the SFILE keyword with the SLN keyword.
SLN(number)
The SLN (Start Line Number) keyword determines where a record format is written
to a display file. The main file description line must contain WORKSTN in positions
36 through 42 and a C or O in positions 17. The DDS for the file must specify the
keyword SLNO(*VAR) for one or more record formats. When you specify the SLN
keyword, the parameter will automatically be defined in the program as a numeric
field with length of 2 and with 0 decimal positions.
Do not use the SLN keyword with the SFILE keyword.
TIMFMT(format{separator})
The TIMFMT keyword allows the specification of a default external time format and
a default separator (which is optional) for all time fields in the program-described
file. If the file on which this keyword is specified is indexed and the key field is a
time, then the time format specified also provides the default external format for the
key field.
270
ILE RPG for AS/400 Reference
File Types and Processing Methods
For a Record-Address file this specifies the external time format of time limits keys
read from the record-address file.
You can specify a different external format for individual input or output time fields
in the file by specifying a time format/separator for the field on the corresponding
input specification (positions 31-35) or output specification (positions 53-57).
See Table 16 on page 189 for valid format and separators. For more information
on external formats, see “Internal and External Formats” on page 159.
USROPN
The USROPN keyword causes the file not to be opened at program initialization.
This gives the programmer control of the file's first open. The file must be explicitly
opened using the OPEN operation in the calculation specifications. This keyword is
not valid for input files designated as primary, secondary, table, or record-address
files, or for output files conditioned by the 1P (first page) indicator.
The USROPN keyword is required for programmer control of only the first file
opening. For example, if a file is opened and later closed by the CLOSE operation,
the programmer can reopen the file (using the OPEN operation) without having
specified the USROPN keyword on the file description specification.
See also “EXTIND(*INUx)” on page 263.
File Types and Processing Methods
Table 27 shows the valid entries for positions 28, 34, and 35 of the file description
specifications for the various file types and processing methods. The methods of
disk file processing include:
¹ Relative-record-number processing
¹ Consecutive processing
¹ Sequential-by-key processing
¹ Random-by-key processing
¹ Sequential-within-limits processing.
Table 27 (Page 1 of 2). Processing Methods for DISK Files
Access
Method
Opcode
Position
28
Position
34
Position
35
Explanation
Random
RRN
CHAIN
Blank
Blank
Blank
Access by physical
order of records
Sequential
Key
READ
READE
READP
READPE
cycle
Blank
Blank
I
Access by key
sequentially
Sequential
Within
Limits
READ
READE
READP
READPE
cycle
L
A, P, G, D,
T, Z, or F
I
Access by key
sequentially controlled by recordaddress-limits file
Chapter 14. File Description Specifications
271
File Types and Processing Methods
Table 27 (Page 2 of 2). Processing Methods for DISK Files
Access
Method
Opcode
Position
28
Position
34
Position
35
Explanation
Sequential
RRN
READ
cycle
Blank
Blank
T
Access sequentially restricted to
RRN numbers in
record-address file
For further information on the various file processing methods, see the section entitled "Methods for Processing Disk Files", in the chapter "Accessing Database Files"
in the ILE RPG for AS/400 Programmer's Guide.
272
ILE RPG for AS/400 Reference
Definition Specification Statement
Chapter 15. Definition Specifications
Definition specifications can be used to define:
¹ Standalone fields
¹ Named constants
¹ Data structures and their subfields
¹ Prototypes
¹ Procedure interface
¹ Prototyped parameters
For more information on data structures, constants, prototypes, and procedure
interfaces, see also Chapter 8, “Defining Data and Prototypes” on page 113 For
more information on data types and data formats, see also Chapter 10, “Data
Types and Data Formats” on page 159.
Arrays and tables can be defined as either a data-structure subfield or a standalone
field. For additional information on defining and using arrays and tables, see also
Chapter 9, “Using Arrays and Tables” on page 143.
Definition specifications can appear in two places within a module or program: in
the main source section and in a subprocedure. Within the main source section,
you define all global definitions. Within a subprocedure, you define the procedure
interface and its parameters as required by the prototype. You also define any local
data items that are needed by the prototyped procedure when it is processed. Any
definitions within a prototyped procedure are local. They are not known to any other
procedures (including the main procedure). For more information on scope, see
“Scope of Definitions” on page 93.
A built-in function(BIF) can be used in the keyword field as a parameter to a
keyword. It is allowed on the definition specification only if the values of all arguments are known at compile time. When specified as parameters for the definition
specification keywords DIM, OCCURS, OVERLAY, and PERRCD, all arguments for
a BIF must be defined earlier in the program. For further information on using
built-in functions, see Chapter 20, “Built-in Functions” on page 357.
Definition Specification Statement
The general layout for the definition specification is as follows:
¹ The definition specification type (D) is entered in position 6
¹ The non-commentary part of the specification extends from position 7 to position 80
– The fixed-format entries extend from positions 7 to 42
– The keyword entries extend from positions 44 to 80
¹ The comments section of the specification extends from position 81 to position
100.
 Copyright IBM Corp. 1994, 1999
273
Definition Specification Statement
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++Comments++++++++++++
Figure 103. Definition Specification Layout
Definition Specification Keyword Continuation Line
If additional space is required for keywords, the keywords field can be continued on
subsequent lines as follows:
¹ Position 6 of the continuation line must contain a D
¹ Positions 7 to 43 of the continuation line must be blank
¹ The specification continues on or past position 44
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
D.....................................Keywords+++++++++++++++++++++++++++++Comments++++++++++++
Figure 104. Definition Specification Keyword Continuation Line Layout
Definition Specification Continued Name Line
A name that is up to 15 characters long can be specified in the Name entry of the
definition specification without requiring continuation. Any name (even one with 15
characters or fewer) can be continued on multiple lines by coding an ellipsis (...) at
the end of the partial name. A name definition consists of the following parts:
1. Zero or more continued name lines. Continued name lines are identified as
having an ellipsis as the last non-blank character in the entry. The name must
begin within positions 7 to 21 and may end anywhere up to position 77 (with an
ellipsis ending in position 80). There cannot be blanks between the start of the
name and the ellipsis character. If any of these conditions is not true, the line is
parsed as a main definition line.
2. One main definition line, containing a name, definition attributes, and keywords.
If a continued name line is coded, the Name entry of the main definition line
may be left blank.
3. Zero or more keyword continuation lines.
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
DContinuedName+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Comments++++++++++++
Figure 105. Definition Specification Continued Name Line Layout
Position 6 (Form Type)
Enter a D in this position for definition specifications.
274
ILE RPG for AS/400 Reference
Definition Specification Statement
Positions 7-21 (Name)
Entry
Explanation
Name
The name of the item being defined.
Blank
Specifies filler fields in data-structure subfield definitions, or an unnamed
data structure in data-structure definitions.
The normal rules for RPG IV symbolic names apply; reserved words cannot be
used (see “Symbolic Names” on page 3). The name can begin in any position in
the space provided. Thus, indenting can be used to indicate the shape of data in
data structures.
For continued name lines, a name is specified in positions 7 through 80 of the continued name lines and positions 7 through 21 of the main definition line. As with the
traditional definition of names, case of the characters is not significant.
For an externally described subfield, a name specified here replaces the externalsubfield name specified on the EXTFLD keyword.
For a prototype parameter definition, the name entry is optional. If a name is specified, the name is ignored. (A prototype parameter is a definition specification with
blanks in positions 24-25 that follows a PR specification or another prototype
parameter definition.)
TIP
If you are defining a prototype and the name specified in positions 7-21 cannot
serve as the external name of the procedure, use the EXTPROC keyword to
specify the valid external name. For example, the external name may be
required to be in lower case, because you are defining a prototype for a procedure written in ILE C.
Position 22 (External Description)
This position is used to identify a data structure or data-structure subfield as
externally described. If a data structure or subfield is not being defined on this
specification, then this field must be left blank.
Entry
Explanation for Data Structures
E
Identifies a data structure as externally described: subfield definitions
are defined externally. If the EXTNAME keyword is not specified, positions 7-21 must contain the name of the externally described file containing the data structure definition.
Blank
Program described: subfield definitions for this data structure follow this
specification.
Entry
Explanation for Subfields
E
Identifies a data-structure subfield as externally described. The specification of an externally described subfield is necessary only when
keywords such as EXTFLD and INZ are used.
Chapter 15. Definition Specifications
275
Definition Specification Statement
Blank
Program described: the data-structure subfield is defined on this specification line.
Position 23 (Type of Data Structure)
This entry is used to identify the type of data structure being defined. If a data
structure is not being defined, this entry must be left blank.
Entry
Explanation
Blank
The data structure being defined is not a program status or data-area
data structure; or a data structure is not being defined on this specification
S
Program status data structure. Only one data structure may be designated as the program status data structure.
U
Data-area data structure.
RPG IV retrieves the data area at initialization and rewrites it at end of
program.
¹ If the DTAARA keyword is specified, the parameter to the DTAARA
keyword is used as the name of the external data area.
¹ If the DTAARA keyword is not specified, the name in positions 7-21
is used as the name of the external data area.
¹ If a name is not specified either by the DTAARA keyword, or by
positions 7-21, *LDA (the local data area) is used as the name of
the external data area.
Positions 24-25 (Definition Type)
Entry
Explanation
Blank
The specification defines either a data structure subfield or a parameter
within a prototype or procedure interface definition.
C
The specification defines a constant. Position 25 must be blank.
DS
The specification defines a data structure.
PR
The specification defines a prototype and the return value, if any.
PI
The specification defines a procedure interface, and the return value if
any.
S
The specification defines a standalone field, array or table. Position 25
must be blank.
Definitions of data structures, prototypes, and procedure interfaces end with the first
definition specification with non-blanks in positions 24-25, or with the first specification that is not a definition specification.
For a list of valid keywords, grouped according to type of definition, please refer to
Table 29 on page 305.
276
ILE RPG for AS/400 Reference
Definition Specification Statement
Positions 26-32 (From Position)
Positions 26-32 may only contain an entry if the location of a subfield within a data
structure is being defined.
|
Entry
Explanation
Blank
A blank FROM position indicates that the value in the TO/LENGTH field
specifies the length of the subfield, or that a subfield is not being defined
on this specification line.
nnnnnnn Absolute starting position of the subfield within a data structure. The
value specified must be from 1 to 65535 for a named data structure
(and from 1 to 9999999 for an unnamed data structure), and rightjustified in these positions.
Reserved Words
Reserved words for the program status data structure or for a file information data structure are allowed (left-justified) in the
FROM-TO/LENGTH fields (positions 26-39). These special reserved
words define the location of the subfields in the data structures.
Reserved words for the program status data structure are *STATUS,
*PROC, *PARM, and *ROUTINE. Reserved words for the file information
data structure (INFDS) are *FILE, *RECORD, *OPCODE, *STATUS, and
*ROUTINE.
Positions 33-39 (To Position / Length)
Entry
Explanation
Blank
If positions 33-39 are blank:
¹ a named constant is being defined on this specification line, or
¹ the standalone field, parameter, or subfield is being defined LIKE
another field, or
¹ the standalone field, parameter, or subfield is of a type where a
length is implied, or
¹ the subfield's attributes are defined elsewhere, or
¹ a data structure is being defined. The length of the data structure is
the maximum value of the subfield To-Positions.
|
nnnnnnn Positions 33-39 may contain a (right-justified) numeric value, from 1 to
65535 for a named data structure (and from 1 to 9999999 for an
unnamed data structure), as follows:
¹ If the From field (position 26-32) contains a numeric value, then a
numeric value in this field specifies the absolute end position of the
subfield within a data structure.
¹ If the From field is blank, a numeric value in this field specifies :
– the length of the entire data structure, or
– the length of the standalone field, or
– the length of the parameter, or
– the length of the subfield. Within the data structure, this subfield
is positioned such that its starting position is greater than the
maximum to-position of all previously defined subfields in the
Chapter 15. Definition Specifications
277
Definition Specification Statement
data structure. Padding is inserted if the subfield is defined with
type basing pointer or procedure pointer to ensure that the subfield is aligned properly.
|
|
|
Note: For graphic or UCS-2 fields, the number specified here is the
number of graphic or UCS-2 characters, NOT the number of
bytes (1 graphic or UCS-2 character = 2 bytes). For numeric
fields, the number specified here is the number of digits (for
packed and zoned numeric fields: 1-30; for binary numeric
fields: 1-9; for integer and unsigned numeric fields: 3, 5, 10,
or 20 ).
|
|
Note: For float numeric fields the number specified is the number
of bytes, NOT the number of digits (4 or 8 bytes).
+|-nnnnn This entry is valid for standalone fields or subfields defined using the
LIKE keyword. The length of the standalone field or subfield being
defined on this specification line is determined by adding or subtracting
the value entered in these positions to the length of the field specified as
the parameter to the LIKE keyword.
|
|
|
Note: For graphic or UCS-2 fields, the number specified here is the
number of graphic or UCS-2 characters, NOT the number of
bytes (1 graphic or UCS-2 character = 2 bytes). For numeric
fields, the number specified here is the number of digits.
Note: For float fields, the entry must be blank or +0. The size of a float
field cannot be changed as with other numerics.
Reserved Words
If positions 26-32 are used to enter special reserved words, this field
becomes an extension of the previous one, creating one large field
(positions 26-39). This allows for reserved words, with names longer
than 7 characters in length, to extend into this field. See “Positions
26-32 (From Position)” on page 277, 'Reserved Words'.
Position 40 (Internal Data Type)
This entry allows you to specify how a standalone field, parameter, or datastructure subfield is stored internally. This entry pertains strictly to the internal representation of the data item being defined, regardless of how the data item is
stored externally (that is, if it is stored externally). To define variable-length character, graphic, and UCS-2 formats, you must specify the keyword VARYING; otherwise, the format will be fixed length.
|
Entry
Explanation
Blank
When the LIKE keyword is not specified:
¹ If the decimal positions entry is blank, then the item is defined as
character
¹ If the decimal positions entry is not blank, then the item is defined
as packed numeric if it is a standalone field or parameter; or as
zoned numeric if it is a subfield.
Note: The entry must be blank when the LIKE keyword is specified.
A
278
ILE RPG for AS/400 Reference
Character (Fixed or Variable-length format)
Definition-Specification Keywords
|
B
Numeric (Binary format)
C
UCS-2 (Fixed or Variable-length format)
D
Date
F
Numeric (Float format)
G
Graphic (Fixed or Variable-length format)
I
Numeric (Integer format)
N
Character (Indicator format)
P
Numeric (Packed decimal format)
S
Numeric (Zoned format)
T
Time
U
Numeric (Unsigned format)
Z
Timestamp
*
Basing pointer or procedure pointer
Positions 41-42 (Decimal Positions)
Positions 41-42 are used to indicate the number of decimal positions in a numeric
subfield or standalone field. If the field is non-float numeric, there must always be
an entry in these positions. If there are no decimal positions enter a zero (0) in
position 42. For example, an integer or unsigned field (type I or U in position 40)
requires a zero for this entry.
Entry
Explanation
Blank
The value is not numeric (unless it is a float field) or has been defined
with the LIKE keyword.
0-30
Decimal positions: the number of positions to the right of the decimal in
a numeric field.
This entry can only be supplied in combination with the TO/Length field. If the
TO/Length field is blank, the value of this entry is defined somewhere else in the
program (for example, through an externally described data base file).
Position 43 (Reserved)
Position 43 must be blank.
Positions 44-80 (Keywords)
Positions 44 to 80 are provided for definition specification keywords. Keywords are
used to describe and define data and its attributes. Use this area to specify any
keywords necessary to fully define the field.
Definition-Specification Keywords
Definition-specification keywords may have no parameters, optional parameters, or
required parameters. The syntax for keywords is as follows:
Keyword(parameter1 : parameter2)
Chapter 15. Definition Specifications
279
Definition-Specification Keywords
where:
¹ Parameter(s) are enclosed in parentheses ( ).
Note: Do not specify parentheses if there are no parameters.
¹ Colons (:) are used to separate multiple parameters.
The following notational conventions are used to show which parameters are
optional and which are required:
¹ Braces { } indicate optional parameters or optional elements of parameters.
¹ An ellipsis (...) indicates that the parameter can be repeated.
¹ A colon (:) separates parameters and indicates that more than one may be
specified. All parameters separated by a colon are required unless they are
enclosed in braces.
¹ A vertical bar (|) indicates that only one parameter may be specified for the
keyword.
¹ A blank separating keyword parameters indicates that one or more of the
parameters may be specified.
Note: Braces, ellipses, and vertical bars are not a part of the keyword syntax and
should not be entered into your source.
If additional space is required for definition-specification keywords, the keyword field
can be continued on subsequent lines. See “Definition Specification Keyword Continuation Line” on page 274 and “Definition Specification Keyword Field” on
page 228.
ALIGN
The ALIGN keyword is used to align float, integer, and unsigned subfields. When
ALIGN is specified, 2-byte subfields are aligned on a 2-byte boundary, 4-byte subfields are aligned on a 4-byte boundary and 8-byte subfields are aligned on an
8-byte boundary. Alignment may be desired to improve performance when
accessing float, integer, or unsigned subfields.
Specify ALIGN on the data structure definition. However, you cannot specify ALIGN
for either the file information data structure (INFDS) or the program status data
structure (PSDS).
Alignment occurs only to data structure subfields defined with length notation and
without the keyword OVERLAY. A diagnostic message is issued if subfields that are
defined either with absolute notation or using the OVERLAY keyword are not properly aligned.
|
|
Pointer subfields are always aligned on a 16-byte boundary whether or not ALIGN
is specified.
See “Aligning Data Structure Subfields” on page 125 for more information.
280
ILE RPG for AS/400 Reference
Definition-Specification Keywords
ALT(array_name)
The ALT keyword is used to indicate that the compile-time or pre-runtime array or
table is in alternating format.
The array defined with the ALT keyword is the alternating array and the array name
specified as the parameter is the main array. The alternate array definition may
precede or follow the main array definition.
The keywords on the main array define the loading for both arrays. The initialization
data is in alternating order, beginning with the main array, as follows:
main/alt/main/alt/...
In the alternate array definition, the PERRCD, FROMFILE, TOFILE, and CTDATA
keywords are not valid.
ALTSEQ(*NONE)
When the ALTSEQ(*NONE) keyword is specified, the alternate collating sequence
will not be used for comparisons involving this field, even when the ALTSEQ
keyword is specified on the control specification. ALTSEQ(*NONE) on Data Definition specifications will be meaningful only if one of ALTSEQ, ALTSEQ(*SRC) or
ALTSEQ(*EXT) is coded in the control specifications. It is ignored if this is not true.
ALTSEQ(*NONE) is a valid keyword for:
¹ Character standalone fields
¹ Character arrays
¹ Character tables
¹ Character subfields
¹ Data structures
¹ Character return values on Procedure Interface or Prototype definitions
¹ Character Prototyped Parameters
ASCEND
The ASCEND keyword is used to describe the sequence of the data in any of the
following:
¹ An array
¹ A table loaded at prerun-time or compile time
¹ A prototyped parameter
See also “DESCEND” on page 284.
Ascending sequence means that the array or table entries must start with the
lowest data entry (according to the collating sequence) and go to the highest. Items
with equal value are allowed.
A prerun-time array or table is checked for the specified sequence at the time the
array or table is loaded with data. If the array or table is out of sequence, control
passes to the RPG IV exception/error handling routine. A run-time array (loaded by
input and/or calculation specifications) is not sequence checked.
Chapter 15. Definition Specifications
281
Definition-Specification Keywords
When ALTSEQ(*EXT) is specified, the alternate collating sequence is used when
checking the sequence of compile-time arrays or tables. If the alternate sequence is
not known until run-time, the sequence is checked at run-time; if the array or table
is out of sequence, control passes to the RPG IV exception/error handling routine.
A sequence (ascending or descending) must be specified if the LOOKUP operation
is used to search an array or table for an entry to determine whether the entry is
high or low compared to the search argument.
If the SORTA operation code is used with an array, and no sequence is specified,
an ascending sequence is assumed.
BASED(basing_pointer_name)
When the BASED keyword is specified for a data structure or standalone field, a
basing pointer is created using the name specified as the keyword parameter.
This basing pointer holds the address (storage location) of the based data structure
or standalone field being defined. In other words, the name specified in positions
7-21 is used to refer to the data stored at the location contained in the basing
pointer.
Note: Before the based data structure or standalone field can be used, the basing
pointer must be assigned a valid address.
If an array is defined as a based standalone field it must be a run-time array.
If a based field is defined within a subprocedure, then both the field and the basing
pointer are local.
|
|
CCSID(number | *DFT)
This keyword sets the CCSID for graphic and UCS-2 definitions.
|
|
|
|
number must be an integer between 0 and 65535. It must be a valid graphic or
UCS-2 CCSID value. A valid graphic CCSID is 65535 or a CCSID with the EBCDIC
double-byte encoding scheme (X'1200'). A valid UCS-2 CCSID has the UCS-2
encoding scheme (x'7200').
|
|
|
For program-described fields, CCSID(number) overrides the defaults set on the
control specification with the CCSID(*GRAPH: *SRC), CCSID(*GRAPH: number), or
CCSID(*UCS2: number) keyword.
|
|
|
CCSID(*DFT) indicates that the default CCSID for the module is to be used. This
is useful when the LIKE keyword is used since the new field would otherwise inherit
the CCSID of the source field.
|
|
|
If the keyword is not specified, the default graphic or UCS-2 CCSID of the module
is assumed. (This keyword is not allowed for graphic fields when CCSID(*GRAPH :
*IGNORE) is specified or assumed).
|
|
If this keyword is not specified and the LIKE keyword is specified, the new field will
have the same CCSID as the LIKE field.
282
ILE RPG for AS/400 Reference
Definition-Specification Keywords
CONST{(constant)}
The CONST keyword is used
¹ To specify the value of a named constant
¹ To indicate that a parameter passed by reference is read-only.
When specifying the value of a named constant, the CONST keyword itself is
optional. That is, the constant value can be specified with or without the CONST
keyword.
The parameter must be a literal, figurative constant, or built-in-function. The constant may be continued on subsequent lines by adhering to the appropriate continuation rules (see “Continuation Rules” on page 225 for further details).
If a named constant is used as a parameter for the keywords DIM, OCCURS,
PERRCD, or OVERLAY, the named constant must be defined prior to its use.
When specifying a read-only reference parameter, you specify the keyword
CONST on the definition specification of the parameter definition on both the prototype and procedure interface. No parameter to the keyword is allowed.
When the keyword CONST is specified, the compiler may copy the parameter to a
temporary and pass the address of the temporary. Some conditions that would
cause this are: the passed parameter is an expression or the passed parameter
has a different format.
Attention!
Do not use this keyword on a prototype definition unless you are sure that the
parameter will not be changed by the called program or procedure.
If the called program or procedure is compiled using a procedure interface with
the same prototype, you do not have to worry about this, since the compiler will
check this for you.
Passing a parameter by constant value has the same advantages as passing by
value. In particular, it allows you to pass literals and expressions.
CTDATA
The CTDATA keyword indicates that the array or table is loaded using compile-time
data. The data is specified at the end of the program following the ** or
**CTDATA(array/table name) specification.
When an array or table is loaded at compilation time, it is compiled along with the
source program and included in the program. Such an array or table does not need
to be loaded separately every time the program is run.
Chapter 15. Definition Specifications
283
Definition-Specification Keywords
DATFMT(format{separator})
The DATFMT keyword specifies the internal date format, and optionally the separator character, for any of these items of type Date: standalone field; data-structure
subfield; prototyped parameter; or return value on a prototype or procedureinterface definition. This keyword will be automatically generated for an externally
described data structure subfield of type Date and determined at compile time.
If DATFMT is not specified, the Date field will have the date format and separator
as specified by the DATFMT keyword on the control specification, if present. If
none is specified on the control specification, then it will have *ISO format.
See Table 13 on page 186 for valid formats and separators. For more information
on internal formats, see “Internal and External Formats” on page 159.
DESCEND
The DESCEND keyword describes the sequence of the data in any of the following:
¹ An array
¹ A table loaded at prerun-time or compile time
¹ A prototyped parameter
See also “ASCEND” on page 281.
Descending sequence means that the array or table entries must start with the
highest data entry (according to the collating sequence) and go to the lowest. Items
with equal value are allowed.
A prerun-time array or table is checked for the specified sequence at the time the
array or table is loaded with data. If the array or table is out of sequence, control
passes to the RPG IV exception/error handling routine. A run-time array (loaded by
input and/or calculation specifications) is not sequence checked.
When ALTSEQ(*EXT) is specified, the alternate collating sequence is used when
checking the sequence of compile-time arrays or tables. If the alternate sequence is
not known until run-time, the sequence is checked at run-time; if the array or table
is out of sequence, control passes to the RPG IV exception/error handling routine.
A sequence (ascending or descending) must be specified if the LOOKUP operation
is used to search an array or table for an entry to determine whether the entry is
high or low compared to the search argument.
If the SORTA operation code is used with an array, and no sequence is specified,
an ascending sequence is assumed.
DIM(numeric_constant)
The DIM keyword defines the number of elements in an array; a table; a prototyped
parameter; or a return value on a prototype or procedure-interface definition.
The numeric constant must have zero (0) decimal positions. It can be a literal, a
named constant or a built-in function.
The constant value must be known at the time the keyword is processed; otherwise, a compile-time error will occur.
284
ILE RPG for AS/400 Reference
Definition-Specification Keywords
DTAARA{(data_area_name)}
The DTAARA keyword is used to associate a standalone field, data structure, datastructure subfield or data-area data structure with an external data area. The
DTAARA keyword has the same function as the *DTAARA DEFINE operation code
(see “*DTAARA DEFINE” on page 510).
On the AS/400 you can create three kinds of data areas:
¹ *CHAR Character
¹ *DEC Numeric
¹ *LGL Logical
You can also create a DDM data area (type *DDM) that points to a data area on a
remote system of one of the three types above.
Only character and numeric types (excluding float numeric) are allowed to be associated with data areas. The actual data area on the system must be of the same
type as the field in the program, with the same length and decimal positions. Indicator fields can be associated with either a logical data area or a character data
area.
If data_area_name is not specified, then the name specified in positions 7-21 is
also the name of the external data area. If data_area_name is specified, then it
must be a valid AS/400 data area name, including *LDA (for the local data area)
and *PDA (for the program initialization parameters data area).
If neither the parameter nor the data-structure name is specified, then the default is
*LDA.
When the DTAARA keyword is specified, the IN, OUT, and UNLOCK operation
codes can be used on the data area.
EXPORT{(external_name)}
The specification of the EXPORT keyword allows a globally defined data structure
or standalone field defined within a module to be used by another module in the
program. The storage for the data item is allocated in the module containing the
EXPORT definition. The external_name parameter, if specified, must be a character
literal or constant.
|
|
|
The EXPORT keyword on the definition specification is used to export data items
and cannot be used to export procedure names. To export a procedure name, use
the EXPORT keyword on the procedure specification.
Note: The initialization for the storage occurs when the program entry procedure
(of the program containing the module) is first called. RPG IV will not do
any further initialization on this storage, even if the procedure ended with
LR on, or ended abnormally on the previous call.
The following restrictions apply when EXPORT is specified:
¹ Only one module may define the data item as exported
¹ You cannot export a field that is specified in the Result-Field entry of a PARM
in the *ENTRY PLIST
Chapter 15. Definition Specifications
285
Definition-Specification Keywords
¹ Unnamed data structures cannot be exported
¹ BASED data items cannot be exported
¹ The same external field name cannot be specified more than once per module
and also cannot be used as an external procedure name
¹ IMPORT and EXPORT cannot both be specified for the same data item.
For a multiple-occurrence data structure or table, each module will contain its own
copy of the occurrence number or table index. An OCCUR or LOOKUP operation in
any module will have only a local impact since the occurrence number or index is
local to each module.
See also “IMPORT{(external_name)}” on page 289.
TIP
The keywords IMPORT and EXPORT allow you to define a "hidden" interface
between modules. As a result, use of these keywords should be limited only to
those data items which are global throughout the application. It is also suggested that this global data be limited to things like global attributes which are
set once and never modified elsewhere.
|
EXTFLD(field_name)
The EXTFLD keyword is used to rename a subfield in an externally described data
structure. Enter the external name of the subfield as the parameter to the EXTFLD
keyword, and specify the name to be used in the program in the Name field (positions 7-21).
The keyword is optional. If not specified, the name extracted from the external definition is used as the data-structure subfield name.
If the PREFIX keyword is specified for the data structure, the prefix will not be
applied to fields renamed with EXTFLD.
EXTFMT(code)
The EXTFMT keyword is used to specify the external data type for compile-time
and prerun-time numeric arrays and tables. The external data type is the format of
the data in the records in the file. This entry has no effect on the format used for
internal processing (internal data type) of the array or table in the program.
Note: The values specified for EXTFMT will apply to the files identified in both the
TOFILE and FROMFILE keywords, even if the specified names are different.
The possible values for the parameter are:
|
286
B
The data for the array or table is in binary format.
C
The data for the array or table is in UCS-2 format.
I
The data for the array or table is in integer format.
L
The data for a numeric array or table element has a preceding (left) plus
or minus sign.
ILE RPG for AS/400 Reference
Definition-Specification Keywords
R
The data for a numeric array or table element has a following (right) plus
or minus sign.
P
The data for the array or table is in packed decimal format.
S
The data for the array or table is in zoned decimal format.
U
The data for the array or table is in unsigned format.
F
The data for the array or table is in float numeric format.
Notes:
1. If the EXTFMT keyword is not specified, the external format defaults to 'S' for
non-float arrays and tables, and to the external display float representation for
float pre-runtime arrays and tables.
2. For compile-time arrays and tables, the only values allowed are S, L, and R,
unless the data type is float, in which case the EXTFMT keyword is not
allowed.
|
|
|
|
3. When EXTFMT(I) or EXTFMT(U) is used, arrays defined as having 1 to 5 digits
will occupy 2 bytes per element. Arrays defined as having 6 to 10 digits will
occupy 4 bytes per element. Arrays defined as having 11 to 20 digits will
occupy 8 bytes per element.
|
|
|
|
|
|
|
|
|
|
4. The default external format for UCS-2 arrays is character. The number of characters allowed for UCS-2 compile-time data is the number of double-byte characters in the UCS-2 array. If graphic data is included in the data, the presence
of double-byte data and the shift-out and shift-in characters in the data will
reduce the actual amount of data that can be placed in the array element; the
rest of the element will be padded with blanks. For example, for a 4-character
UCS-2 array, only one double-byte character can be specified in the compiletime data; if the compile-time data were 'oXXi', where 'XX' is converted to the
UCS-2 character U'yyyy', the UCS-2 element would contain the value
U'yyyy002000200020'.
EXTNAME(file_name{:format_name})
The EXTNAME keyword is used to specify the name of the file which contains the
field descriptions used as the subfield description for the data structure being
defined.
The file_name parameter is required. Optionally a format name may be specified to
direct the compiler to a specific format within a file. If format_name parameter is not
specified the first record format is used.
If the data structure definition contains an E in position 22, and the EXTNAME
keyword is not specified, the name specified in positions 7-21 is used.
The compiler will generate the following definition specification entries for all fields
of the externally described data structure:
¹ Subfield name (Name will be the same as the external name, unless renamed
by keyword EXTFLD or the PREFIX keyword on a definition specification is
used to apply a prefix).
¹ Subfield length
Chapter 15. Definition Specifications
287
Definition-Specification Keywords
¹ Subfield internal data type (will be the same as the external type, unless the
CVTOPT control specification keyword or command parameter is specified for
the type. In that case the data type will be character).
All data structure keywords are allowed with the EXTNAME keyword.
EXTPGM(name)
The EXTPGM keyword indicates the external name of the program whose prototype is being defined. The name can be a character constant or a character variable. When EXTPGM is specified, then a dynamic call will be done.
If neither EXTPGM or EXTPROC is specified, then the compiler assumes that you
are defining a prototype for a procedure, and assigns it the external name found in
positions 7-21.
Any parameters defined by a prototype with EXTPGM must be passed by reference. In addition, you cannot define a return value.
EXTPROC(name)
The EXTPROC keyword indicates the external name of the procedure whose prototype is being defined. The name can be a character constant or a procedure
pointer. When EXTPROC is specified, then a bound call will be done.
If neither EXTPGM or EXTPROC is specified, then the compiler assumes that you
are defining a procedure, and assigns it the external name found in positions 7-21.
If the name specified for EXTPROC (or the prototype name, if neither EXTPGM or
EXTPROC are specified) starts with "CEE" or an underscore ('_'), the compiler will
treat this as a system built-in. To avoid confusion with system provided APIs, you
should not name your procedures starting with "CEE".
For example, to define the prototype for the procedure SQLAllocEnv, that is in the
service program QSQCLI, the following definition specification could be coded:
D SQLEnv
PR
EXTPROC('SQLAllocEnv')
If a procedure pointer is specified, it must be assigned a valid address before it is
used in a call. It should point to a procedure whose return value and parameters
are consistent with the prototype definition.
Figure 106 on page 289 shows an example of the EXTPROC keyword with a procedure pointer as its parameter.
288
ILE RPG for AS/400 Reference
Definition-Specification Keywords
* Assume you are calling a procedure that has a procedure
* pointer as the EXTPROC. Here is how the prototype would
* be defined:
D DspMsg
PR
10A
EXTPROC(DspMsgPPtr)
D Msg
32767A
D Length
4B 0 VALUE
* Here is how you would define the prototype for a procedure
* that DspMsgPPtr could be assigned to.
D MyDspMsg
PR
LIKE(DspMsg)
D Msg
32767A
D Length
4B 0 VALUE
* Before calling DSPMSG, you would assign DSPMSGPPTR
* to the actual procedure name of MyDspMsg, that is
* MYDSPMSG.
C
EVAL
DspMsgPPtr = %paddr('MYDSPMSG')
C
EVAL
Reply = DspMsg(Msg, %size(Msg))
...
P MyDspMsg
B
Figure 106. Using EXTPROC with a Procedure Pointer
FROMFILE(file_name)
The FROMFILE keyword is used to specify the file with input data for the preruntime array or table being defined. The FROMFILE keyword must be specified for
every prerun-time array or table used in the program.
See also “TOFILE(file_name)” on page 304.
IMPORT{(external_name)}
The IMPORT keyword specifies that storage for the data item being defined is allocated in another module, but may be accessed in this module. The external_name
parameter, if specified, must be a character literal or constant.
If a name is defined as imported but no module in the program contains an
exported definition of the name, an error will occur at link time. See
“EXPORT{(external_name)}” on page 285.
|
|
|
|
The IMPORT keyword on the definition specification is used to import data items
and cannot be used to import procedure names. Procedure names are imported
implicitly, to all modules in the program, when the EXPORT keyword is specified on
a procedure specification.
The following restrictions apply when IMPORT is specified:
¹ The data item may not be initialized (the INZ keyword is not allowed). The
exporting module manages all initialization for the data.
¹ An imported field cannot be defined as a compile-time or prerun-time array or
table, or as a data area. (Keywords CTDATA, FROMFILE, TOFILE, EXTFMT,
PERRCD, and DTAARA are not allowed.)
¹ An imported field may not be specified as an argument to the RESET operation
code since the initial value is defined in the exporting module.
¹ You cannot specify an imported field in the Result-Field entry of a PARM in the
*ENTRY PLIST.
Chapter 15. Definition Specifications
289
Definition-Specification Keywords
¹ You cannot define an imported field as based (the keyword BASED is not
allowed).
¹ This keyword is not allowed for unnamed data structures.
¹ The only other keywords allowed are DIM, EXTNAME, LIKE, OCCURS, and
PREFIX.
¹ The same external field name cannot be specified more than once per module
and also cannot be used as an external procedure name.
For a multiple-occurrence data structure or table, each module will contain its own
copy of the occurrence number or table index. An OCCUR or LOOKUP operation in
any module will have only a local impact since the occurrence number or index is
local to each module.
INZ{(initial value)}
The INZ keyword initializes the standalone field, data structure, or data-structure
subfield to the default value for its data type or, optionally, to the constant specified
in parentheses. For a program described data structure, no parameter is allowed
for the INZ keyword. For an externally described data structure, only the *EXTDFT
parameter is allowed.
|
|
|
The constant specified must be consistent with the type being initialized. The constant can be a literal, named constant, figurative constant, built-in function, or one
of the special values *SYS, *JOB, *EXTDFT or *USER. When initializing Date or
Time data type fields or named constants with Date or Time values, the format of
the literal must be consistent with the default format as derived from the Control
specification, regardless of the actual format of the date or time field.
|
|
|
|
|
|
A numeric field may be initialized with any type of numeric literal. However, a float
literal can only be used with a float field. Any numeric field can be initialized with a
hexadecimal literal of 16 digits or fewer. In this case, the hexadecimal literal is considered an unsigned numeric value.
|
|
|
|
|
Specifying INZ(*EXTDFT) initializes externally described data-structure subfields
with the default values from the DFT keyword in the DDS. If no DFT or constant
value is specified, the DDS default value for the field type is used. You can override
the value specified in the DDS by coding INZ with or without a parameter on the
subfield specification.
|
|
|
|
Specifying INZ(*EXTDFT) on the external data structure definition, initializes all
externally described subfields to their DDS default values. If the externally
described data structure has additional program described subfields, these are initialized to the RPG default values.
|
When using INZ(*EXTDFT), take note of the following:
|
|
¹ If the DDS value for a date or time field is not in the RPG internal format, the
value will be converted to the internal format in effect for the program.
|
¹ External descriptions must be in physical files.
|
|
¹ If *NULL is specified for a null-capable field in the DDS, the compiler will use
the DDS default value for that field as the initial value.
|
|
¹ If DFT('') is specified for a varying length field, the field will be initialized with a
string of length 0.
290
ILE RPG for AS/400 Reference
Definition-Specification Keywords
|
¹ INZ(*EXTDFT) is not allowed if the CVTOPT option is in effect.
|
|
|
|
Specifying INZ(*USER) intializes any character field or subfield to the name of the
current user profile. Character fields must be at least 10 characters long. If the field
is longer than 10 characters, the user name is left-justified in the field with blanks in
the remainder.
|
|
Date fields can be initialized to *SYS or *JOB. Time and Timestamp fields can be
initialized to *SYS.
A data structure, data-structure subfield, or standalone field defined with the INZ
keyword cannot be specified as a parameter on an *ENTRY PLIST.
Note: When the INZ parameter is not specified:
¹ Static standalone fields and subfields of initialized data structures are
initialized to their RPG default initial values (for example, blanks for
character, 0 for numeric).
|
¹ Subfields of uninitialized data structures (INZ not specified on the definition specification for the data structure) are initialized to blanks
(regardless of their data type).
This keyword is not valid in combination with BASED or IMPORT.
LIKE(RPG_name)
The LIKE keyword is used to define an item like an existing one. When the LIKE
keyword is specified, the item being defined takes on the length and the data
format of the item specified as the parameter. Standalone fields, prototypes, parameters, and data-structure subfields may be defined using this keyword. The parameter of LIKE can be a standalone field, a data structure, a data structure subfield, a
parameter in a procedure interface definition, or a prototype name. The data type
entry (position 40) must be blank.
|
This keyword is similar to the *LIKE DEFINE operation code (see “*LIKE DEFINE”
on page 508). However, it differs from *LIKE DEFINE in that the defined data takes
on the data format and CCSID as well as the length.
|
Note: Attributes such as ALTSEQ(*NONE), NOOPT, ASCEND, CONST and null
capability are not inherited from the parameter of LIKE by the item defined.
Only the data type, length, decimal positions, and CCSID are inherited.
If the parameter of LIKE is a prototype, then the item being defined will have the
same data type as the return value of the prototype. If there is no return value, then
an error message is issued.
Here are some considerations for using the LIKE keyword with different data types:
¹ For character fields, the number specified in the To/Length entry is the
number of additional (or fewer) characters.
|
¹ For numeric fields, the number specified in the To/Length entry is the number
of additional (or fewer) digits. For integer or unsigned fields, adjustment values
must be such that the resulting number of digits for the field are 3, 5, 10, or 20.
For float fields, length adjustment is not allowed.
Chapter 15. Definition Specifications
291
Definition-Specification Keywords
¹ For graphic or UCS-2 fields, the number specified in the To/Length entry is
the number of additional (or fewer) graphic or UCS-2 characters (1 graphic or
UCS-2 character = 2 bytes).
|
|
|
¹ For date, time, timestamp, basing pointer, or procedure pointer fields, the
To/Length entry (positions 33-39) must be blank.
When LIKE is used to define an array, the DIM keyword is still required to define
the array dimensions. However, DIM(%elem(array)) can be used to define an array
exactly like another array.
The following are examples of defining data using the LIKE keyword.
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D.....................................Keywords+++++++++++++++++++++++++++++
*
* Define a field like another with a length increase of 5 characters.
*
D Name
S
20
D Long_name
S
+5
LIKE(Name)
*
* Define a data structure subfield array with DIM(20) like another
* field and initialize each array element with the value *ALL'X'.
* Also, declare another subfield of type pointer immediately
* following the first subfield. Pointer is implicitly defined
* with a length of 16 bytes
*
D Struct
DS
D
Dim20
LIKE(Name) DIM(20) INZ(*ALL'X')
D
Pointer
*
*
* Define a field which is based on the *LDA. Take the length and type
* of the field from the field 'Name'.
*
D Lda_fld
S
LIKE(Name) DTAARA(*LDA)
Figure 107. Defining fields LIKE other fields
NOOPT
The NOOPT keyword indicates that no optimization is to be performed on the
standalone field, parameter or data structure for which this keyword is specified.
Specifying NOOPT ensures that the content of the data item is the latest assigned
value. This may be necessary for those fields whose values are used in exception
handling.
Note: The optimizer may keep some values in registers and restore them only to
storage at predefined points during normal program execution. Exception
handling may break this normal execution sequence, and consequently
program variables contained in registers may not be returned to their
assigned storage locations. As a result, when those variables are used in
exception handling, they may not contain the latest assigned value. The
NOOPT keyword will ensure their currency.
If a data item which is to be passed by reference is defined with the NOOPT
keyword, then any prototype or procedure interface parameter definition must also
292
ILE RPG for AS/400 Reference
Definition-Specification Keywords
have the NOOPT keyword specified. This requirement does not apply to parameters passed by value.
TIP
Any data item defined in an OPM RPG/400 program is implicitly defined with
NOOPT. So if you are creating a prototype for an OPM program, you should
specify NOOPT for all parameters defined within the prototype. This will avoid
errors for any users of the prototype.
All keywords allowed for standalone field definitions, parameters, or data structure
definitions are allowed with NOOPT.
OCCURS(numeric_constant)
The OCCURS keyword allows the specification of the number of occurrences of a
multiple-occurrence data structure.
The numeric_constant parameter must be a value greater than 0 with no decimal
positions. It can be a numeric literal, a built-in function returning a numeric value, or
a numeric constant. The constant value must be known at the time the keyword is
processed; otherwise, a compile-time error will occur.
This keyword is not valid for a program status data structure, a file information data
structure, or a data area data structure.
If a multiple occurrence data structure contains pointer subfields, the distance
between occurrences must be an exact multiple of 16 because of system storage
restrictions for pointers. This means that the distance between occurrences may be
greater than the length of each occurrence.
The following is an example showing the storage allocation of a multiple occurrence
data structure with pointer subfields.
Chapter 15. Definition Specifications
293
Definition-Specification Keywords
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... *
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D DS1
DS
OCCURS(2)
D
POINTER
16*
D
FLD5
5
D DS2
DS
OCCURS(2)
D
CHAR16
16
D
CHR5
5
Allocation of fields in storage. The occurrences of DS1 are 32 bytes apart,
while the occurrences of DS2 are 21 bytes apart.
DS1 OCCURRENCE 1
POINTER
FLD5
DS1 OCCURRENCE 2
(fill)
POINTER
DS2 OCCURRENCE 1
DS2 OCCURRENCE 2
CHAR16
CHAR16
CHR5
FLD5
(fill)
CHR5
Figure 108. Storage Allocation of Multiple Occurrence Data Structure with Pointer Subfields
OPDESC
The OPDESC keyword specifies that operational descriptors are to be passed with
the parameters that are defined within a prototype.
When OPDESC is specified, operational descriptors are passed with all character
or graphic parameters that are passed by reference. If you attempt to retrieve an
operational descriptor for a parameter passed by value, an error will result.
|
Note: Operational descriptors are not passed for UCS-2 fields.
Using CALLP with a prototyped procedure whose prototype contains OPDESC is
the same as calling a procedure using CALLB (D). Operational descriptors are also
passed for procedures called within expressions.
The keyword applies both to a prototype definition and to a procedure-interface
definition. It cannot be used with the EXTPGM keyword.
For an example of the OPDESC keyword, see the service program example in the
ILE RPG for AS/400 Programmer's Guide.
OPTIONS(*NOPASS *OMIT *VARSIZE *STRING *RIGHTADJ)
The OPTIONS keyword is used to specify one or more parameter passing options:
¹ Whether a parameter must be passed
¹ Whether the special value *OMIT can be passed for the parameter passed by
reference.
¹ Whether a parameter that is passed by reference can be shorter in length than
is specified in the prototype.
294
ILE RPG for AS/400 Reference
Definition-Specification Keywords
¹ Whether the called program or procedure is expecting a pointer to a nullterminated string, allowing you to specify a character expression as the passed
parameter.
|
|
|
|
|
|
When OPTIONS(*NOPASS) is specified on a definition specification, the parameter
does not have to be passed on the call. Any parameters following that specification
must also have *NOPASS specified. When the parameter is not passed to a
program or procedure, the called program or procedure will simply function as if the
parameter list did not include that parameter. If the unpassed parameter is
accessed in the called program or procedure, unpredictable results will occur.
When OPTIONS(*OMIT) is specified, then the value *OMIT is allowed for that
parameter. *OMIT is only allowed for CONST parameters and parameters which
are passed by reference. For more information on omitted parameters, see the
chapter on calling programs and procedures in ILE RPG for AS/400 Programmer's
Guide.
OPTIONS(*VARSIZE) is valid only for parameters passed by reference that have a
character, graphic, or UCS-2 data type, or that represent an array of any type.
When OPTIONS(*VARSIZE) is specified, the passed parameter may be shorter or
longer in length than is defined in the prototype. It is then up to the called program
or subprocedure to ensure that it accesses only as much data as was passed. To
communicate the amount of data passed, you can either pass an extra parameter
containing the length, or use operational descriptors for the subprocedure. For
variable-length fields, you can use the %LEN built-in function to determine the
current length of the passed parameter.
When OPTIONS(*VARSIZE) is omitted for fixed-length fields, you must pass at
least as much data as is required by the prototype; for variable-length fields, the
parameter must have the same declared maximum length as indicated on the definition.
|
|
|
|
|
Note: For the parameter passing options *NOPASS, *OMIT, and *VARSIZE, it is
up to the programmer of the procedure to ensure that these options are
handled. For example, if OPTIONS(*NOPASS) is coded and you choose to
pass the parameter, the procedure must check that the parameter was
passed before it accesses it. The compiler will not do any checking for this.
When OPTIONS(*STRING) is specified for a basing pointer parameter passed by
value or by constant-reference, you may either pass a pointer or a character
expression. If you pass a character expression, a temporary value will be created
containing the value of the character expression followed by a null-terminator
(x'00'). The address of this temporary value will be passed to the called program or
procedure.
|
|
|
|
|
|
When OPTIONS(*RIGHTADJ) is specified for a CONST or VALUE parameter in a
function prototype, the character, graphic, or UCS-2 parameter value is right
adjusted. This keyword is not allowed for a varying length parameter within a procedure prototype. Varying length values may be passed as parameters on a procedure call where the corresponding parameter is defined with
OPTIONS(*RIGHTADJ).
Chapter 15. Definition Specifications
295
Definition-Specification Keywords
You can specify more than one option. For example, to specify that an optional
parameter can be shorter than the prototype indicates, you would code
OPTIONS(*VARSIZE : *NOPASS).
The following example shows how to code a prototype and procedure that use
OPTIONS(*NOPASS) to indicate that a parameter is optional.
* The following prototype describes a procedure that expects
* either one or two parameters.
D FormatAddress
PR
45A
D
City
20A
CONST
D
Province
20A
CONST OPTIONS(*NOPASS)
* The first call to FormatAddress only passes one parameter. The
* second call passes both parameters.
C
EVAL
A = Address('North York')
C
EVAL
A = Address('Victoria' : 'B.C.')
C
RETURN
*---------------------------------------------------------------* FormatAddress:
* This procedure must check the number of parameters since the
* second was defined with OPTIONS(*NOPASS).
* It should only use the second parameter if it was passed.
*---------------------------------------------------------------P FormatAddress
B
D FormatAddress
PI
45A
D
City
20A
CONST
D
ProvParm
20A
CONST OPTIONS(*NOPASS)
D Province
S
20A
INZ('Ontario')
* Set the local variable Province to the value of the second
* parameter if it was passed. Otherwise let it default to
* 'Ontario' as it was initialized.
C
IF
%PARMS > 1
C
EVAL
Province = ProvParm
C
ENDIF
* Return the city and province in the form City, Province
* for example 'North York, Ontario'
C
RETURN
%TRIMR(City) + ',' + Province
P FormatAddress
E
Figure 109. Using OPTIONS(*NOPASS) to Indicate that a Parameter is Optional
The following example shows how to code a prototype and procedure using
OPTIONS(*OMIT) to indicate that the special value *OMIT may be passed as a
parameter.
296
ILE RPG for AS/400 Reference
Definition-Specification Keywords
FQSYSPRT
O
F
10
PRINTER USROPN
* The following prototype describes a procedure that allows
* the special value *OMIT to be passed as a parameter.
* If the parameter is passed, it is set to '1' if an error
* occurred, and '0' otherwise.
D OpenFile
PR
D
Error
1A
OPTIONS(*OMIT)
C
SETOFF
10
* The first call to OpenFile assumes that no error will occur,
* so it does not bother with the error code and passes *OMIT.
C
CALLP
OpenFile(*OMIT)
* The second call to OpenFile passes an indicator so that
* it can check whether an error occurred.
C
CALLP
OpenFile(*IN10)
C
IF
*IN10
C
... an error occurred
C
ENDIF
C
RETURN
*---------------------------------------------------------------* OpenFile
* This procedure must check the number of parameters since the
* second was defined with OPTIONS(*NOPASS).
* It should only use the second parameter if it was passed.
*---------------------------------------------------------------P OpenFile
B
D OpenFile
PI
D
Error
1A
OPTIONS(*OMIT)
D SaveIn01
S
1A
* Save the current value of indicator 01 in case it is being
* used elsewhere.
C
EVAL
SaveIn01 = *IN01
* Open the file. *IN01 will indicate if an error occurs.
C
OPEN
QSYSPRT
01
* If the Error parameter was passed, update it with the indicator
C
IF
%ADDR(Error) <> *NULL
C
EVAL
Error = *IN01
C
ENDIF
* Restore *IN01 to its original value.
C
EVAL
*IN01 = SaveIn01
P OpenFile
E
Figure 110. Using OPTIONS(*OMIT)
The following example shows how to code a prototype and procedure allowing
variable-length parameters, using OPTIONS(*VARSIZE).
Chapter 15. Definition Specifications
297
Definition-Specification Keywords
* The following prototype describes a procedure that allows
* both a variable-length array and a variable-length character
* field to be passed. Other parameters indicate the lengths.
D Search
PR
5U 0
D
SearchIn
50A
OPTIONS(*VARSIZE)
D
DIM(100) CONST
D
ArrayLen
5U 0 VALUE
D
ArrayDim
5U 0 VALUE
D
SearchFor
50A
OPTIONS(*VARSIZE) CONST
D
FieldLen
5U 0 VALUE
D Arr1
S
1A
DIM(7) CTDATA PERRCD(7)
D Arr2
S
10A
DIM(3) CTDATA
D Elem
S
5U 0
* Call Search to search an array of 7 elements of length 1 with
* a search argument of length 1. Since the '*' is in the 5th
* element of the array, Elem will have the value 5.
C
EVAL
Elem = Search(Arr1 :
C
%SIZE(Arr1) : %ELEM(Arr1) :
C
'*' : 1)
* Call Search to search an array of 3 elements of length 10 with
* a search argument of length 4. Since 'Pink' is not in the
* array, Elem will have the value 0.
C
EVAL
Elem = Search(Arr2 :
C
%SIZE(Arr2) : %ELEM(Arr2) :
C
'Pink' : 4)
C
RETURN
Figure 111 (Part 1 of 2). Using OPTIONS(*VARSIZE)
298
ILE RPG for AS/400 Reference
Definition-Specification Keywords
*-----------------------------------------------------------* Search:
*
Searches for SearchFor in the array SearchIn. Returns
*
the element where the value is found, or 0 if not found.
*
The character parameters can be of any length or
*
dimension since OPTIONS(*VARSIZE) is specified for both.
*-----------------------------------------------------------P Search
B
D Search
PI
5U 0
D
SearchIn
50A
OPTIONS(*VARSIZE)
D
DIM(100) CONST
D
ArrayLen
5U 0 VALUE
D
ArrayDim
5U 0 VALUE
D
SearchFor
50A
OPTIONS(*VARSIZE) CONST
D
FieldLen
5U 0 VALUE
D I
S
5U 0
* Check each element of the array to see if it the same
* as the SearchFor. Use the dimension that was passed as
* a parameter rather than the declared dimension. Use
* %SUBST with the length parameter since the parameters may
* not have the declared length.
C
1
DO
ArrayDim
I
5 0
* If this element matches SearchFor, return the index.
C
IF
%SUBST(SearchIn(I) : 1 : ArrayLen)
C
= %SUBST(SearchFor : 1 : FieldLen)
C
RETURN
I
C
ENDIF
C
ENDDO
* No matching element was found.
C
RETURN
0
P Search
E
**CTDATA ARR1
A2$@*jM
**CTDATA ARR2
Red
Blue
Yellow
Figure 111 (Part 2 of 2). Using OPTIONS(*VARSIZE)
The following example shows how to use OPTIONS(*STRING) to code a prototype
and procedure that use a null-terminated string parameter.
Chapter 15. Definition Specifications
299
Definition-Specification Keywords
* The following prototype describes a procedure that expects
* a null-terminated string parameter. It returns the length
* of the string.
D StringLen
PR
5U 0
D
Pointer
*
VALUE OPTIONS(*STRING)
D P
S
*
D Len
S
5U 0
* Call StringLen with a character literal. The result will be
* 4 since the literal is 4 bytes long.
C
EVAL
Len = StringLen('abcd')
* Call StringLen with a pointer to a string. Use ALLOC to get
* storage for the pointer, and use %STR to initialize the storage
* to 'My string¬' where '¬' represents the null-termination
* character x'00'.
* The result will be 9 which is the length of 'My string'.
C
ALLOC
25
P
C
EVAL
%STR(P:25) = 'My string'
C
EVAL
Len = StringLen(P)
* Free the storage.
C
DEALLOC
P
C
RETURN
*-----------------------------------------------------------* StringLen:
*
Returns the length of the string that the parameter is
*
pointing to.
*-----------------------------------------------------------P StringLen
B
D StringLen
PI
5U 0
D
Pointer
*
VALUE OPTIONS(*STRING)
C
RETURN
%LEN(%STR(Pointer))
P StringLen
E
Figure 112. Using OPTIONS(*STRING)
OVERLAY(name{:pos | *NEXT})
The OVERLAY keyword overlays the storage of one subfield with that of another
subfield, or with that of the data structure itself. This keyword is allowed only for
data structure subfields.
The Name-entry subfield overlays the storage specified by the name parameter at
the position specified by the pos parameter. If pos is not specified, it defaults to 1.
Note: The pos parameter is in units of bytes, regardless of the types of the subfields.
|
|
|
Specifying OVERLAY(name:*NEXT) positions the subfield at the next available
position within the overlaid field. (This will be the first byte past all other subfields
prior to this subfield that overlay the same subfield.)
The following rules apply to keyword OVERLAY:
1. The name parameter must be the name of a subfield defined previously in the
current data structure, or the name of the current data structure.
2. The pos parameter (if specified) must be a value greater than 0 with no
decimal positions. It can be a numeric literal, a built-in function returning a
numeric value, or a numeric constant. If pos is a named constant, it must be
defined prior to this specification.
300
ILE RPG for AS/400 Reference
Definition-Specification Keywords
3. The OVERLAY keyword is not allowed when the From-Position entry is not
blank.
4. If the name parameter is a subfield, the subfield being defined must be contained completely within the subfield specified by the name parameter.
5. Alignment of subfields defined using the OVERLAY keyword must be done
manually. If they are not correctly aligned, a warning message is issued.
6. If the subfield specified as the first parameter for the OVERLAY keyword is an
array, the OVERLAY keyword applies to each element of the array. That is, the
field being defined is defined as an array with the same number of elements.
The first element of this array overlays the first element of the overlaid array,
the second element of this array overlays the second element of the overlaid
array, and so on. No array keywords may be specified for the subfield with the
OVERLAY keyword in this situation. (Refer to Figure 113) See also “SORTA
(Sort an Array)” on page 657.
If the subfield name, specified as the first parameter for the OVERLAY
keyword, is an array and its element length is longer than the length of the
subfield being defined, the array elements of the subfield being defined are not
stored contiguously. Such an array is not allowed as the Result Field of a
PARM operation or in Factor 2 or the Result Field of a MOVEA operation.
|
|
|
7. If the ALIGN keyword is specified for the data structure, subfields defined with
OVERLAY(name:*NEXT) are aligned to their preferred alignment. Pointer subfields are always aligned on a 16-byte boundary.
|
|
8. If a subfield with overlaying subfields is not otherwise defined, the subfield is
implicitly defined as follows:
|
|
|
|
¹ The start position is the first available position in the data structure.
¹ The length is the minimum length that can contain all overlaying subfields.
If the subfield is defined as an array, the length will be increased to ensure
proper alignment of all overlaying subfields.
Examples
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... *
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++++++++++
D DataStruct
DS
D
A
10
DIM(5)
D
B
5
OVERLAY(A)
D
C
5
OVERLAY(A:6)
Allocation of fields in storage:
A(1)
B(1)
A(2)
C(1)
B(2)
A(3)
C(2)
B(3)
A(4)
C(3)
B(4)
A(5)
C(4)
B(5)
C(5)
Figure 113. Storage Allocation of Subfields with Keywords DIM and OVERLAY
Chapter 15. Definition Specifications
301
Definition-Specification Keywords
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... *
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D DataStruct
DS
D
A
5
D
B
1
OVERLAY(A) DIM(4)
Allocation of fields in storage:
A
B(1)
B(2)
B(3)
B(4)
Figure 114. Storage Allocation of Subfields with Keywords DIM and OVERLAY
|
|
The following example shows two equivalent ways of defining subfield overlay
positions: explicitly with (name:pos) and implicitly with (name:*NEXT).
|
|
|
|
|
|
|
|
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... *
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
* Define subfield overlay positions explicitly
D DataStruct
DS
D
PartNumber
10A
D
Family
3A
OVERLAY(PartNumber)
D
Sequence
6A
OVERLAY(PartNumber:4)
D
Language
1A
OVERLAY(PartNumber:10)
|
|
|
|
|
|
|
|
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... *
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
* Define subfield overlay positions with *NEXT
D DataStruct
DS
D
PartNumber
D
Family
3A
OVERLAY(PartNumber)
D
Sequence
6A
OVERLAY(PartNumber:*NEXT)
D
Language
1A
OVERLAY(PartNumber:*NEXT)
|
Figure 115. Defining Subfield Overlay Positions with *NEXT
PACKEVEN
The PACKEVEN keyword indicates that the packed field or array has an even
number of digits. The keyword is only valid for packed program-described datastructure subfields defined using FROM/TO positions. For a field or array element
of length N, if the PACKEVEN keyword is not specified, the number of digits is 2N 1; if the PACKEVEN keyword is specified, the number of digits is 2(N-1).
PERRCD(numeric_constant)
The PERRCD keyword allows you to specify the number of elements per record for
a compile-time or a prerun-time array or table. If the PERRCD keyword is not specified, the number of elements per record defaults to one (1).
The numeric_constant parameter must be a value greater than 0 with no decimal
positions. It can be a numeric literal, a built-in function returning a numeric value, or
a numeric constant. If the parameter is a named constant, it must be defined prior
to this specification.
302
ILE RPG for AS/400 Reference
Definition-Specification Keywords
The PERRCD keyword is valid only when the keyword FROMFILE, TOFILE, or
CTDATA is specified.
PREFIX(prefix_string{:nbr_of_char_replaced})
The PREFIX keyword allows the specification of a string which is to be prefixed to
the subfield names of the externally described data structure being defined. In addition, you can optionally specify a numeric value to indicate the number of characters, if any, in the existing name to be replaced. If the parameter
'nbr_of_char_replaced' is not specified, then the string is attached to the beginning
of the name.
If the 'nbr_of_char_replaced' is specified, it must represent a numeric value
between 0 and 9 with no decimal places. Specifying a value of zero is the same as
not specifying 'nbr_of_char_replaced' at all. For example, the specification
PREFIX(YE:3) would change the field name 'YTDTOTAL' to 'YETOTAL'.
The 'nbr_of_char_replaced' parameter can be a numeric literal, a built-in function
that returns a numeric value, or a numeric constant. If it is a named constant, then
the constant must be defined prior to the specification containing the PREFIX
keyword. In addition, if it is a built-in function, all parameters to the built-in
functionmust be defined prior to the specification containing the keyword PREFIX.
The following rules apply:
¹ Subfields that are explicitly renamed using the EXTFLD keyword are not
affected by this keyword.
¹ The total length of a name after applying the prefix must not exceed the
maximum length of an RPG field name.
¹ If the number of characters in the name to be prefixed is less than or equal to
the value represented by the 'nbr_of_char_replaced' parameter, then the entire
name is replaced by the prefix_string.
PROCPTR
The PROCPTR keyword defines an item as a procedure pointer. The internal DataType field (position 40) must contain a *.
STATIC
The STATIC keyword specifies that the data item is to be stored in static storage,
and thereby hold its value across calls to the procedure in which it is defined. The
keyword can only be used within a subprocedure. All global fields are static.
The data item is initialized when the program or service program it is contained in
is first activated. It is not reinitialized again, even if reinitialization occurs for global
definitions as part of normal cycle processing.
If STATIC is not specified, then any locally defined data item is stored in automatic
storage. Data stored in automatic storage is initialized at the beginning of every
call. When a procedure is called recursively, each invocation gets its own copy of
the storage.
Chapter 15. Definition Specifications
303
Definition-Specification Keywords
TIMFMT(format{separator})
The TIMFMT keyword allows the specification of an internal time format, and
optionally the time separator, for any of these items of type Time: standalone field;
data-structure subfield; prototyped parameter; or return value on a prototype or
procedure-interface definition. This keyword will be automatically generated for an
externally described data-structure subfield of type Time.
If TIMFMT is not specified, the Time field will have the time format and separator
as specified by the TIMFMT keyword on the control specification, if present. If none
is specified on the control specification, then it will have *ISO format.
See Table 16 on page 189 for valid formats and separators. For more information
on internal formats, see “Internal and External Formats” on page 159.
TOFILE(file_name)
The TOFILE keyword allows the specification of a target file to which a prerun-time
or compile-time array or table is to be written.
If an array or table is to be written, specify the file name of the output or combined
file as the keyword parameter. This file must also be defined in the file description
specifications. An array or table can be written to only one output device.
If an array or table is assigned to an output file, it is automatically written if the LR
indicator is on at program termination. The array or table is written after all other
records are written to the file.
If an array or table is to be written to the same file from which it was read, the
same file name that was specified as the FROMFILE parameter must be specified
as the TOFILE parameter. This file must be defined as a combined file (C in position 17 on the file description specification).
VALUE
The VALUE keyword indicates that the parameter is passed by value rather than by
reference. Parameters can be passed by value when the procedure they are associated with are called using a procedure call.
The VALUE keyword cannot be specified for a parameter if its prototype was
defined using the EXTPGM keyword. Calls to programs require that parameters be
passed by reference.
The rules for what can be passed as a value parameter to a called procedure are
the same as the rules for what can be assigned using the EVAL operation. The
parameter received by the procedure corresponds to the left-hand side of the
expression; the passed parameter corresponds to the right-hand side. See “EVAL
(Evaluate expression)” on page 529 for more information.
VARYING
|
|
|
|
The VARYING keyword indicates that a character, graphic, or UCS-2 field, defined
on the definition specifications, should have a variable-length format. If this keyword
is not specified for character, graphic, or UCS-2 fields, they are defined as fixed
length.
304
ILE RPG for AS/400 Reference
Summary According to Definition Specification Type
|
|
For more information, see “Variable-Length Character, Graphic and UCS-2
Formats” on page 165.
Summary According to Definition Specification Type
Table 28 lists the required and allowed entries for each definition specification type.
Table 29 and Table 30 on page 307 list the keywords allowed for each definition
specification type.
In each of these tables, an R indicates that an entry in these positions is required
and an A indicates that an entry in these positions is allowed.
Table 28. Required/Allowed Entries for each Definition Specification Type
Type
Pos.
7-21
Name
Pos.
22
External
A
Pos.
23 DS
Type
Pos.
24-25
Defn.
Type
A
R
Data
Structure
A
Data
Structure
Subfield
A
External
Subfield
A
Standalone
Field
R
R
Named
Constant
R
R
Prototype
R
R
Prototype
Parameter
A
Procedure
Interface
A
Procedure
Interface
Parameter
R
Pos.
26-32
From
Pos.
33-39
To /
Length
Pos.
40
Datatype
Pos.
41-42
Decimal
Pos.
Pos.
44-80
Keywords
A
A
A
A
A
A
A
R
A
A
A
A
A
R
R
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
A
Table 29 (Page 1 of 2). Data Structure, Standalone Fields, and Named Constants
Keywords
Keyword
ALIGN
Data
Structure
A
ASCEND
BASED
External
Subfield
Standalone
Field
A
A
A
A
A
A
A
A
A
Named
Constant
A
ALT
ALTSEQ
Data
Structure
Subfield
A
A
Chapter 15. Definition Specifications
305
Summary According to Definition Specification Type
Table 29 (Page 2 of 2). Data Structure, Standalone Fields, and Named Constants
Keywords
Keyword
|
Data
Structure
CCSID
Data
Structure
Subfield
External
Subfield
A
Standalone
Field
A
CONST1
R
CTDATA2
A
DATFMT
A
DESCEND
A
A
A
DIM
A
A
A
DTAARA2
A
EXPORT2
A
IMPORT2
A
INZ
A
LIKE
A
OCCURS
A
A
A
A
A
A
A
A
A
A
A
A
A
A
OVERLAY
A
PACKEVEN
A
PERRCD
A
A
A
A
PROCPTR
STATIC3
A
A
NOOPT
PREFIX4
A
A
FROMFILE2
|
A
A
EXTFMT
|
A
A
EXTFLD
EXTNAME4
Named
Constant
A
A
A
A
TIMFMT
A
TOFILE2
A
VARYING
A
A
A
A
A
Notes:
1. When defining a named constant, the keyword is optional, but the parameter to the
keyword is required. For example, to assign a named constant the value '10', you
could specify either CONST('10') or '10'.
2. This keyword applies only to global definitions.
3. This keyword applies only to local definitions.
|
4. This keyword applies only to externally described data structures.
306
ILE RPG for AS/400 Reference
Table 30. Prototype, Procedure Interface, and Parameter Keywords
Keyword
Prototype (PR)
Procedure Interface (PI)
PR or PI Parameter
ASCEND
A
CONST
A
DATFMT
A
A
DESCEND
A
DIM
A
EXTPGM
A
EXTPROC
A
LIKE
A
A
A
A
A
NOOPT
OPDESC
A
A
A
A
OPTIONS
A
PROCPTR
A
A
A
TIMFMT
A
A
A
VALUE
VARYING
A
A
A
A
Named Constant Keyword
¹ “CONST{(constant)}” on page 283
Chapter 15. Definition Specifications
307
308
ILE RPG for AS/400 Reference
Input Specification Statement
Chapter 16. Input Specifications
For a program-described input file, input specifications describe the types of
records within the file, the sequence of the types of records, the fields within a
record, the data within the field, indicators based on the contents of the fields,
control fields, fields used for matching records, and fields used for sequence
checking. For an externally described file, input specifications are optional and can
be used to add RPG IV functions to the external description.
Detailed information for the input specifications is given in:
¹ Entries for program described files
¹ Entries for externally described files
Input Specification Statement
The general layout for the Input specification is as follows:
¹ the input specification type (I) is entered in position 6
¹ the non-commentary part of the specification extends from position 7 to position
80
¹ the comments section of the specification extends from position 81 to position
100
Program Described
For program described files, entries on input specifications are divided into the following categories:
¹ Record identification entries (positions 7 through 46), which describe the input
record and its relationship to other records in the file.
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
IFilename++SqNORiPos1+NCCPos2+NCCPos3+NCC..................................Comments++++++++++++
I.........And..RiPos1+NCCPos2+NCCPos3+NCC..................................Comments++++++++++++
Figure 116. Program Described Record Layout
¹ Field description entries (positions 31 through 74), which describe the fields in
the records. Each field is described on a separate line, below its corresponding
record identification entry.
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
I........................Fmt+SPFrom+To+++DcField+++++++++L1M1FrPlMnZr......Comments++++++++++++
Figure 117. Program Described Field Layout
 Copyright IBM Corp. 1994, 1999
309
Record Identification Entries
Externally Described
For externally described files, entries on input specifications are divided into the
following categories:
¹ Record identification entries (positions 7 through 16, and 21 through 22), which
identify the record (the externally described record format) to which RPG IV
functions are to be added.
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
IRcdname+++....Ri..........................................................Comments++++++++++++
Figure 118. Externally Described Record Layout
¹ Field description entries (positions 21 through 30, 49 through 66, and 69
through 74), which describe the RPG IV functions to be added to the fields in
the record. Field description entries are written on the lines following the corresponding record identification entries.
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
I..............Ext-field+..................Field+++++++++L1M1..PlMnZr......Comments++++++++++++
Figure 119. Externally Described Field Layout
Program Described Files
Position 6 (Form Type)
An I must appear in position 6 to identify this line as an input specification statement.
Record Identification Entries
Record identification entries (positions 7 through 46) for a program described file
describe the input record and its relationship to other records in the file.
Positions 7-16 (File Name)
Entry
Explanation
A valid file name
Same file name that appears on the file description specifications for the
input file.
Enter the name of the file to be described in these positions. This name must be
the same name defined for the file on the file description specifications. This file
must be an input file, an update file, or a combined file. The file name must be
entered on the first record identification line for each file and can be entered on
subsequent record identification lines for that file. All entries describing one input
file must appear together; they cannot be mixed with entries for other files.
310
ILE RPG for AS/400 Reference
Record Identification Entries
Positions 16-18 (Logical Relationship)
Entry
Explanation
AND
More than three identification codes are used.
OR
Two or more record types have common fields.
An unlimited number of AND/OR lines can be used. For more information see “AND
Relationship” on page 315 and “OR Relationship” on page 316.
Positions 17-18 (Sequence)
Entry
Explanation
Any two alphabetic characters
The program does not check for special sequence.
Any two-digit number
The program checks for special sequence within the group.
The numeric sequence entry combined with the number (position 19) and option
(position 20) entries causes the program to check the sequence of input records
within a file. If the sequence is not correct, control passes to the RPG IV
exception/error handling routine. If AND or OR lines are specified, the sequence
entry is made on the main record line of the group, not on the AND or OR lines.
Alphabetic and numeric entries can be made for different records (different record
identification lines) in the same file, but records with alphabetic entries must be
specified before records with numeric entries.
Alphabetic Entries
Enter any two alphabetic characters in these positions when no sequence checking
is to be done. It is common programming practice to specify these codes in a
sequence that aids in program documentation. However, it is not necessary to use
unique alphabetic entries.
Numeric Entries
Enter a unique numeric code in positions 17 and 18 if one record type must be
read before another record type in a file. Numeric entries must be in ascending
order, starting with 01, but need not be consecutive. When a numeric entry is
used, the appropriate entries must be made in positions 19 and 20.
To specify sequence checking, each record type must have a record identification
code, and the record types must be numbered in the order in which they should
appear. This order is checked as the records are read. If a record type is out of
sequence, control passes to the RPG IV exception/error handling routine.
Sequence numbers ensure only that all records of each record type precede the
records of higher sequence-numbered record types. The sequence numbers do not
ensure that records within a record type are in any certain order. Sequence
numbers are unrelated to control levels and do not provide for checking data in
fields of a record for a special sequence. Use positions 65 and 66 (matching fields)
to indicate that data in fields of a record should be checked for a special sequence.
Chapter 16. Input Specifications
311
Record Identification Entries
Position 19 (Number)
Entry
Explanation
Blank
The program does not check record types for a special sequence (positions 17 and 18 have alphabetic entries).
1
Only one record of this type can be present in the sequenced group.
N
One or more records of this type can be present in the sequenced
group.
This entry must be used when a numeric entry is made in positions 17 and 18. If
an alphabetic entry is made in positions 17 and 18, this entry must be blank.
Position 20 (Option)
Entry
Explanation
Blank
The record type must be present if sequence checking is specified.
O
The record type is optional (that is, it may or may not be present) if
sequence checking is specified.
This entry must be blank if positions 17 and 18 contain an alphabetic entry.
Sequence checking of record types has no meaning when all record types within a
file are specified as optional (alphabetic entry in positions 17 and 18 or O entry in
position 20).
Positions 21-22 (Record Identifying Indicator, or **)
Entry
Explanation
Blank
No indicator is used.
01-99
General indicator.
L1-L9 or LR
Control level indicator used for a record identifying indicator.
H1-H9
Halt indicator.
U1-U8
External indicator.
RT
Return indicator.
**
Lookahead record (not an indicator). Lookahead can be used only with a
primary or secondary file.
The indicators specified in these positions are used in conjunction with the record
identification codes (positions 23 through 46).
Indicators
Positions 21 and 22 associate an indicator with the record type defined on this line.
The normal entry is one of the indicators 01 to 99; however, the control level indicators L1 through L9 and LR can be used to cause certain total steps to be processed. If a control level indicator is specified, lower control level indicators are not
set on. The halt indicators H1 through H9 can be used to stop processing. The
return indicator (RT) is used to return to the calling program.
312
ILE RPG for AS/400 Reference
Record Identification Entries
When a record is selected for processing and satisfies the conditions indicated by
the record identification codes, the appropriate record identifying indicator is set on.
This indicator can be used to condition calculation and output operations. Record
identifying indicators can be set on or set off by the programmer. However, at the
end of the cycle, all record identifying indicators are set off before another record is
selected.
Lookahead Fields
The entry of ** is used for the lookahead function. This function lets you look at
information in the next record in a file. You can look not only at the file currently
selected for processing but also at other files present but not selected during this
cycle.
Field description lines must contain From and To entries in the record, a field
name, and decimal positions if the field is numeric. Note that a lookahead field may
not be specified as a field name on input specifications or as a data structure name
on definition specifications or as a Result Field on Calculation Specifications.
Positions 17 and 18 must contain an alphabetic entry. The lookahead fields are
defined in positions 49 through 62 of the lines following the line containing ** in
positions 21 and 22. Positions 63 through 80 must be blank.
Any or all of the fields in a record can be defined as lookahead fields. This definition applies to all records in the file, regardless of their type. If a field is used
both as a lookahead field and as a normal input field, it must be defined twice with
different names.
The lookahead function can be specified only for primary and secondary files and
can be specified only once for a file. It cannot be used for full procedural files (identified by an F in position 18 of the file description specifications), or with AND or OR
lines.
When a record is being processed from a combined file or an update file, the data
in the lookahead field is the same as the data in the record being processed, not
the data in the next record.
The lookahead function causes information in the file information data structure to
be updated with data pertaining to the lookahead record, not to the current primary
record.
If an array element is specified as a lookahead field, the entire array is classified as
a lookahead field.
So that the end of the file can be recognized, lookahead fields are filled with a
special value when all records in the file have been processed. For character fields,
this value is all '9's; for all other data types, this value is the same as *HIVAL.
Positions 23-46 (Record Identification Codes)
Entries in positions 23 through 46 identify each record type in the input file. One to
three identification codes can be entered on each specification line. More than
three record identification codes can be specified on additional lines with the
AND/OR relationship. If the file contains only one record type, the identification
codes can be left blank; however, a record identifying indicator entry (positions 21
and 22) and a sequence entry (positions 17 and 18) must be made.
Chapter 16. Input Specifications
313
Record Identification Entries
|
|
Note: Record identification codes are not applicable for graphic or UCS-2 data
type processing: record identification is done on single byte positions only.
Three sets of entries can be made in positions 23 through 46: 23 through 30, 31
through 38, and 39 through 46. Each set is divided into four groups: position, not,
code part, and character.
The following table shows which categories use which positions in each set.
Category
23-30
31-38
39-46
Position
23-27
31-35
39-43
Not
28
36
44
Code Part
29
37
45
Character
30
38
46
Entries in these sets need not be in sequence. For example, an entry can be made
in positions 31 through 38 without requiring an entry in positions 23 through 30.
Entries for record identification codes are not necessary if input records within a file
are of the same type. An input specification containing no record identification code
defines the last record type for the file, thus allowing the handling of any record
types that are undefined. If no record identification codes are satisfied, control
passes to the RPG IVexception/error handling routine.
Positions 23-27, 31-35, and 39-43 (Position)
Entry
Explanation
Blank
No record identification code is present.
1-32766
The position that contains the record identification code in the record.
In these positions enter the position that contains the record identification code in
each record. The position containing the code must be within the record length
specified for the file. This entry must be right-adjusted, but leading zeros can be
omitted.
Positions 28, 36, and 44 (Not)
Entry
Explanation
Blank
Record identification code must be present.
N
Record identification code must not be present.
Enter an N in this position if the code described must not be present in the specified record position.
Positions 29, 37, and 45 (Code Part)
Entry
Explanation
C
Entire character
Z
Zone portion of character
D
Digit portion of character.
This entry specifies what part of the character in the record identification code is to
be tested.
314
ILE RPG for AS/400 Reference
Record Identification Entries
Character (C): The C entry indicates that the complete structure (zone and digit)
of the character is to be tested.
Zone (Z): The Z entry indicates that the zone portion of the character is to be
tested. The zone entry causes the four high-order bits of the character entry to be
compared with the zone portion of the character in the record position specified in
the position entry. The following three special cases are exceptions:
¹ The hexadecimal representation of an & (ampersand) is 50. However, when an
ampersand is coded in the character entry, it is treated as if its hexadecimal
representation were C0, that is, as if it had the same zone as A through I. An
ampersand in the input data satisfies two zone checks: one for a hexadecimal
5 zone, the other for a hexadecimal C zone.
¹ The hexadecimal representation of a - (minus sign) is 60. However, when a
minus sign is coded in the character entry, it is treated as if its hexadecimal
representation were D0, that is, as if it had the same zone as J through R. A
minus sign in the input data satisfies two zone checks: one for a hexadecimal 6
zone, the other for a hexadecimal D zone.
¹ The hexadecimal representation of a blank is 40. However, when a blank is
coded in the character entry, it is treated as if its hexadecimal representation
were F0, that is, as if it had the same zone as 0 through 9. A blank in the input
data satisfies two zone checks: one for a hexadecimal 4 zone, the other for a
hexadecimal F zone.
Digit (D): The D entry indicates that the digit portion of the character is to be
tested. The four low-order bits of the character are compared with the character
specified by the position entry.
Positions 30, 38, and 46 (Character)
In this position enter the identifying character that is to be compared with the character in the position specified in the input record.
The check for record type always starts with the first record type specified. If data
in a record satisfies more than one set of record identification codes, the first record
type satisfied determines the record types.
When more than one record type is specified for a file, the record identification
codes should be coded so that each input record has a unique set of identification
codes.
AND Relationship
The AND relationship is used when more than three record identification codes
identify a record.
To use the AND relationship, enter at least one record identification code on the
first line and enter the remaining record identification codes on the following lines
with AND coded in positions 16 through 18 for each additional line used. Positions
7 through 15, 19 through 20, and 46 through 80 of each line with AND in positions
16 through 18 must be blank. Sequence, and record-identifying-indicator entries are
made in the first line of the group and cannot be specified in the additional lines.
An unlimited number of AND/OR lines can be used on the input specifications.
Chapter 16. Input Specifications
315
Field Description Entries
OR Relationship
The OR relationship is used when two or more record types have common fields.
To use the OR relationship, enter OR in positions 16 and 17. Positions 7 through
15, 18 through 20, and 46 through 80 must be blank. A record identifying indicator
can be entered in positions 21 and 22. If the indicator entry is made and the record
identification codes on the OR line are satisfied, the indicator specified in positions
21 and 22 on that line is set on. If no indicator entry is made, the indicator on the
preceding line is set on.
An unlimited number of AND/OR lines can be used on the input specifications.
Field Description Entries
The field description entries (positions 31 through 74) must follow the record identification entries (positions 7 through 46) for each file.
Position 6 (Form Type)
An I must appear in position 6 to identify this line as an input specification statement.
Positions 7-30 (Reserved)
Positions 7-30 must be blank.
Positions 31-34 (Data Attributes)
Positions 31-34 specify the external format for a date, time, or variable-length character, graphic, or UCS-2 field.
|
If this entry is blank for a date or time field, then the format/separator specified for
the file (with either DATFMT or TIMFMT or both) is used. If there is no external
date or time format specified for the file, then an error message is issued. See
Table 13 on page 186 and Table 16 on page 189 for valid date and time formats.
|
|
For character, graphic, or UCS-2 data, the *VAR data attribute is used to specify
variable-length input fields. If this entry is blank for character, graphic, or UCS-2
data, then the external format must be fixed length. The internal and external
format must match, if the field is defined elsewhere in the program. For more information on variable-length fields, see “Variable-Length Character, Graphic and
UCS-2 Formats” on page 165.
For more information on external formats, see “Internal and External Formats” on
page 159.
Position 35 (Date/Time Separator)
Position 35 specifies a separator character to be used for date/time fields. The &
(ampersand) can be used to specify a blank separator. See Table 13 on page 186
and Table 16 on page 189 for date and time formats and their default separators.
For an entry to be made in this field, an entry must also be made in positions 31-34
(date/time external format).
316
ILE RPG for AS/400 Reference
Field Description Entries
Position 36 (Data Format)
|
Entry
Explanation
Blank
The input field is in zoned decimal format or is a character field.
A
Character field (fixed- or variable-length format)
C
UCS-2 field (fixed- or variable-length format)
G
Graphic field (fixed- or variable-length format)
B
Numeric field (binary format)
F
Numeric field (float format)
I
Numeric field (integer format)
L
Numeric field with a preceding (left) plus or minus sign (zoned decimal
format)
N
Character field (Indicator format)
P
Numeric field (packed decimal format)
R
Numeric field with a following (right) plus or minus sign (zoned decimal
format)
S
Numeric field (zoned decimal format)
U
Numeric field (unsigned format)
D
Date field — the date field has the external format specified in positions
31-34 or the default file date format.
T
Time field — the time field has the external format specified in positions
31-34 or the default file time format.
Z
Timestamp field
The entry in position 36 specifies the data type, and if numeric, the external data
format of the data in the program-described file.
Positions 37-46 (Field Location)
Entry
Explanation
Two 1- to 5-digit numbers
Beginning of a field (from) and end of a field (to).
This entry describes the location and size of each field in the input record. Positions
37 through 41 specify the location of the field's beginning position; positions 42
through 46 specify the location of the field's end position. To define a singleposition field, enter the same number in positions 37 through 41 and in positions 42
through 46. Numeric entries must be right-adjusted; leading zeros can be omitted.
The maximum number of positions in the input record for each type of field is as
follows:
Positions
Type of Field
30
Zoned decimal numeric (30 digits)
16
Packed numeric (30 digits)
4
Binary (9 digits)
Chapter 16. Input Specifications
317
Field Description Entries
|
8
Integer (20 digits)
|
8
Unsigned (20 digits)
8
Float (8 bytes)
31
Numeric with leading or trailing sign (30 digits)
10
Date
8
Time
26
Timestamp
32766
Character (32766 characters)
32766
Graphic or UCS-2 (16383 double-byte characters)
32766
Variable-Length Character (32764 characters)
32766
Variable-Length Graphic or UCS-2 (16382 double-byte characters)
32766
Data structure
|
|
The maximum size of a character or data structure field specified as a program
described input field is 32766 since that is the maximum record length for a file.
|
|
When specifying a variable-length character, graphic, or UCS-2 input field, the
length includes the 2 byte length prefix.
For arrays, enter the beginning position of the array in positions 37 through 41 and
the ending position in positions 42 through 46. The array length must be an integral
multiple of the length of an element. The From-To position does not have to
account for all the elements in the array. The placement of data into the array starts
with the first element.
Positions 47-48 (Decimal Positions)
|
Entry
Explanation
Blank
Character, graphic, UCS-2, float, date, time, or timestamp field
0-30
Number of decimal positions in numeric field.
This entry, used with the data format entry in position 36, describes the format of
the field. An entry in this field identifies the input field as numeric (except float
numeric); if the field is numeric, an entry must be made. The number of decimal
positions specified for a numeric field cannot exceed the length of the field.
Positions 49-62 (Field Name)
Entry
Explanation
Symbolic name
Field name, data structure name, data structure subfield name, array
name, array element, PAGE, PAGE1-PAGE7, *IN, *INxx, or *IN(xx).
These positions name the fields of an input record that are used in an RPG
IVprogram. This name must follow the rules for symbolic names.
To refer to an entire array on the input specifications, enter the array name in positions 49 through 62. If an array name is entered in positions 49 through 62, control
318
ILE RPG for AS/400 Reference
Field Description Entries
level (positions 63-64), matching fields (positions 65 and 66), and field indicators
(positions 67 through 68) must be blank.
To refer to an element of an array, specify the array name, followed by an index
enclosed within parentheses. The index is either a numeric field with zero decimal
positions or the actual number of the array element to be used. The value of the
index can vary from 1 to n, where n is the number of elements within the array.
Positions 63-64 (Control Level)
Entry
Explanation
Blank
This field is not a control field. Control level indicators cannot be used
with full procedural files.
L1-L9
This field is a control field.
Positions 63 and 64 indicate the fields that are used as control fields. A change in
the contents of a control field causes all operations conditioned by that control level
indicator and by all lower level indicators to be processed.
A split control field is a control field that is made up of more than one field, each
having the same control level indicator. The first field specified with that control
level indicator is placed in the high-order position of the split control field, and the
last field specified with the same control level indicator is placed in the low-order
position of the split control field.
|
Binary, float, integer, character varying, graphic varying, UCS-2 and unsigned fields
cannot be used as control fields.
Positions 65-66 (Matching Fields)
Entry
Explanation
Blank
This field is not a match field.
M1-M9
This field is a match field.
This entry is used to match the records of one file with those of another or to
sequence check match fields within one file. Match fields can be specified only for
fields in primary and secondary files.
|
Binary, float, integer, character varying, graphic varying, UCS-2, and unsigned
fields cannot be used as match fields.
Match fields within a record are designated by an M1 through M9 code entered in
positions 65 and 66 of the appropriate field description specification line. A
maximum of nine match fields can be specified.
The match field codes M1 through M9 can be assigned in any sequence. For
example, M3 can be defined on the line before M1, or M1 need not be defined at
all.
When more than one match field code is used for a record, all fields can be considered as one large field. M1 or the lowest code used is the rightmost or low-order
position of the field. M9 or the highest code used is the leftmost or high-order position of the field.
Chapter 16. Input Specifications
319
Field Description Entries
The ALTSEQ (alternate collating sequence) and FTRANS (file translation) keywords
on the control specification can be used to alter the collating sequence for match
fields.
If match fields are specified for only a single sequential file (input, update, or combined), match fields within the file are sequence checked. The MR indicator is not
set on and cannot be used in the program. An out-of-sequence record causes the
RPG IV exception/error handling routine to be given control.
In addition to sequence checking, match fields are used to match records from the
primary file with those from secondary files.
Positions 67-68 (Field Record Relation)
Entry
Explanation
Blank
The field is common to all record types.
01-99
General indicators.
L1-L9
Control level indicators.
MR
Matching record indicator.
U1-U8
External indicators.
H1-H9
Halt indicators.
RT
Return indicator.
Field record relation indicators are used to associate fields within a particular record
type when that record type is one of several in an OR relationship. This entry
reduces the number of lines that must be written.
The field described on a line is extracted from the record by the RPG IVprogram
only when the indicator coded in positions 67 and 68 is on or when positions 67
and 68 are blank. When positions 67 and 68 are blank, the field is common to all
record types defined by the OR relationship.
Field record relation indicators can be used with control level fields (positions 63
and 64) and matching fields (positions 65 and 66).
Positions 69-74 (Field Indicators)
Entry
Explanation
Blank
No indicator specified
01-99
General indicators
H1-H9
Halt indicator
U1-U8
External indicators
RT
Return indicator.
Entries in positions 69 through 74 test the status of a field or of an array element
as it is read into the program. Field indicators are specified on the same line as the
field to be tested. Depending on the status of the field (plus, minus, zero, or blank),
the appropriate indicator is set on and can be used to condition later specifications.
The same indicator can be specified in two positions, but it should not be used for
320
ILE RPG for AS/400 Reference
Record Identification Entries
all three positions. Field indicators cannot be used with arrays that are not indexed
or look-ahead fields.
|
|
|
Positions 69 and 70 (plus) and positions 71 and 72 (minus) are valid for numeric
fields only. Positions 73 and 74 can be used to test a numeric field for zeros or a
character, graphic, or UCS-2 field for blanks.
The field indicators are set on if the field or array element meets the condition
specified when the record is read. Each field indicator is related to only one record
type; therefore, the indicators are not reset (on or off) until the related record is
read again or until the indicator is defined in some other specification.
Externally Described Files
Position 6 (Form Type)
An I must appear in position 6 to identify this line as an input specifications statement.
Record Identification Entries
When the description of an externally described file is retrieved by the compiler, the
record definitions are also retrieved. To refer to the record definitions, specify the
record format name in the input, calculation, and output specifications of the
program. Input specifications for an externally described file are required if:
¹ Record identifying indicators are to be specified.
¹ A field within a record is to be renamed for the program.
¹ Control level or matching field indicators are to be used.
¹ Field indicators are to be used.
The field description specifications must immediately follow the record identification
specification for an externally described file.
A record line for an externally described file defines the beginning of the override
specifications for the record. All specifications following the record line are part of
the record override until another record format name or file name is found in positions 7 through 16 of the input specifications. All record lines that pertain to an
externally described file must appear together; they cannot be mixed with entries
for other files.
Positions 7-16 (Record Name)
Enter one of the following:
¹ The external name of the record format. (The file name cannot be used for an
externally described file.)
¹ The RPG IV name specified by the RENAME keyword on the file description
specifications if the external record format was renamed. A record format name
can appear only once in positions 7 through 16 of the input specifications for a
program.
Chapter 16. Input Specifications
321
Field Description Entries
Positions 17-20 (Reserved)
Positions 17 through 20 must be blank.
Positions 21-22 (Record Identifying Indicator)
The specification of record identifying indicators in these positions is optional but, if
present, follows the rules as described under “Program Described Files” on
page 310 earlier in this chapter, except for look-ahead specifications, which are
not allowed for an externally described file.
Positions 23-80 (Reserved)
Positions 23-80 must be blank.
Field Description Entries
The field description specifications for an externally described file can be used to
rename a field within a record for a program or to specify control level, field indicator, and match field functions. The field definitions (attributes) are retrieved from
the externally described file and cannot be changed by the program. If the attributes of a field are not valid to an RPG IVprogram (such as numeric length greater
than 30 digits), the field cannot be used. Diagnostic checking is done on fields contained in an external record format in the same way as for source statements.
Normally, externally described input fields are only read during input operations if
the field is actually used elsewhere in the program. If DEBUG or DEBUG(*YES) is
specified, all externally described input fields will be read even if they are not used
in the program.
Positions 7-20 (Reserved)
Positions 7 through 20 must be blank.
Positions 21-30 (External Field Name)
If a field within a record in an externally described file is to be renamed, enter the
external name of the field in these positions. A field may have to be renamed
because the name is the same as a field name specified in the program and two
different names are required.
Positions 31-48 (Reserved)
Positions 31 through 48 must be blank.
Positions 49-62 (Field Name)
The field name entry is made only when it is required for the RPG IVfunction (such
as control levels) added to the external description. The field name entry contains
one of the following:
¹ The name of the field as defined in the external record description (if 10 characters or less).
¹ The name specified to be used in the program that replaced the external name
specified in positions 21 through 30.
The field name must follow the rules for using symbolic names.
322
ILE RPG for AS/400 Reference
Field Description Entries
Indicators are not allowed to be null-capable.
Positions 63-64 (Control Level)
This entry indicates whether the field is to be used as a control field in the program.
|
Entry
Explanation
Blank
This field is not a control field.
L1-L9
This field is a control field.
Null-capable and UCS-2 fields cannot be used as control fields.
Note: For externally described files, split control fields are combined in the order
in which the fields are specified on the data description specifications
(DDS), not in the order in which the fields are specified on the input specifications.
Positions 65-66 (Matching Fields)
This entry indicates whether the field is to be used as a match field.
|
Entry
Explanation
Blank
This field is not a match field.
M1-M9
This field is a match field.
Null-capable and UCS-2 fields cannot be used as matching fields.
See “Positions 65-66 (Matching Fields)” on page 319 for more information on
match fields.
Positions 67-68 (Reserved)
Positions 67 and 68 must be blank.
Positions 69-74 (Field Indicators)
Entry
Explanation
Blank
No indicator specified
01-99
General indicators
H1-H9
Halt indicators
U1-U8
External indicators
RT
Return indicator.
Field indicators are allowed for null-capable fields only if the ALWNULL(*USRCTL)
keyword is specified on a control specification or as a command parameter.
If a field is a null-capable field and the value is null, the indicator is set off.
See “Positions 69-74 (Field Indicators)” on page 320 for more information.
Chapter 16. Input Specifications
323
Field Description Entries
Positions 75-80 (Reserved)
Positions 75 through 80 must be blank.
324
ILE RPG for AS/400 Reference
Calculation Specification Statement
Chapter 17. Calculation Specifications
Calculation specifications indicate the operations done on the data in a program.
Calculation specifications within the main source section must be grouped in the
following order:
¹ Detail calculations
¹ Total calculations
¹ Subroutines
Calculation specifications for subprocedures include two groups:
¹ Body of the subprocedure
¹ Subroutines
Calculations within the groups must be specified in the order in which they are to
be done.
Note: If the keyword NOMAIN is specified on the control specification, then only
declarative calculation specifications are allowed in the main source section.
See Chapter 22, “Operation Codes” on page 427 for details on how the calculation
specification entries must be specified for individual operation codes.
The calculation specification can also be used to enter SQL statements into an ILE
RPG program. See the ILE RPG for AS/400 Programmer's Guide and the DB2
UDB for AS/400 SQL Reference for more information.
Calculation Specification Statement
The general layout for the calculation specification is as follows:
¹ The calculation specification type (C) is entered in position 6
¹ The non-commentary part of the specification extends from position 7 to position 80. These positions are divided into three parts that specify the following:
– When calculations are done:
The control level indicator and the conditioning indicators specified in positions 7 through 11 determine when and under what conditions the calculations are to be done.
– What kind of calculations are done:
The entries specified in positions 12 through 70 (12 through 80 for operations that use extended factor 2, see “Calculation Extended Factor 2
Specification Statement” on page 331 and Chapter 21, “Expressions” on
page 411) specify the kind of calculations done, the data (such as fields or
files) upon which the operation is done, and the field that contains the
results of the calculation.
– What tests are done on the results of the operation:
Indicators specified in positions 71 through 76 are used to test the results
of the calculations and can condition subsequent calculations or output
 Copyright IBM Corp. 1994, 1999
325
Calculation Specification Statement
operations. The resulting indicator positions have various uses, depending
on the operation code. For the uses of these positions, see the individual
operation codes in Chapter 22, “Operation Codes” on page 427.
¹ The comments section of the specification extends from position 81 to position
100
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....Comments++++++++++++
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++++Comments++++++++++++
Figure 120. Calculation Specification Layout
Calculation Specification Extended Factor-2 Continuation Line
The Extended Factor-2 field can be continued on subsequent lines as follows:
¹ position 6 of the continuation line must contain a C
¹ positions 7 to 35 of the continuation line must be blank
¹ the specification continues on or past position 36
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
C.............................Extended-factor2-continuation++++++++++++++++Comments++++++++++++
Figure 121. Calculation Specification Extended Factor-2 Continuation Line
Position 6 (Form Type)
A C must appear in position 6 to identify this line as a calculation specification
statement.
Positions 7-8 (Control Level)
326
Entry
Explanation
Blank
The calculation operation is done at detail calculation time for each
program cycle if the indicators in positions 9 through 11 allow it; or the
calculation is part of a subroutine. Blank is also used for declarative
operation codes.
L0
The calculation operation is done at total calculation time for each
program cycle.
L1-L9
The calculation operation is done at total calculation time when the
control level indicator is on. The indicator is set on either through a level
break or as the result of an input or calculation operation.
LR
The calculation operation is done after the last record has been processed or after the LR indicator has been set on.
SR
The calculation operation is part of an RPG IV subroutine. A blank entry
is also valid for calculations that are part of a subroutine.
AN, OR
Indicators on more than one line condition the calculation.
ILE RPG for AS/400 Reference
Calculation Specification Statement
Control Level Indicators
The L0 entry is used in positions 7 and 8 to indicate that the calculation is always
done during total calculation time.
If indicators L1 through L9 are specified in positions 7 and 8, the calculation is
processed at total calculation time only when the specified indicator is on.
Remember that, if L1 through L9 are set on by a control break, all lower level indicators are also set on. If positions 7 and 8 are blank, the calculation is done at
detail time calculation, is a statement within a subroutine, is a declarative statement, or is a continuation line.
The following operations can be specified within total calculations with positions 7
and 8 blank: PLIST, PARM, KLIST, KFLD, TAG, DEFINE, and ELSE. (Conditioning
indicators in positions 9 through 11 are not allowed with these operations.) In addition, all the preceding operations except TAG and ELSE can be specified anywhere
within the calculations, even between an ENDSR operation of one subroutine and
the BEGSR operation of the next subroutine or after the ENDSR operation for the
last subroutine.
Note: Control indicators cannot be specified in subprocedures.
Last Record Indicator
The LR Indicator, if specified in positions 7 and 8, causes the calculation to be
done during the last total calculation time. Note that the LR indicator cannot be
specified in subprocedures.
If there is a primary file but no secondary files in the program, the LR indicator is
set on after the last input record has been read, the calculations specified for the
record have been done, and the detail output for the last record read has been
completed.
If there is more than one input file (primary and secondary), the programmer determines which files are to be checked for end-of-file by entering an E in position 19 of
the file description specifications. LR is set on when all files with an end-of-file
specification have been completely read, when detail output for the last record in
these files has been completed, and after all matching secondary records have
been processed.
When the LR indicator is set on after the last input record has been read, all control
indicators L1 through L9 defined to the program are also set on.
Subroutine Identifier
An SR entry in positions 7 and 8 may optionally be used for operations within subroutines as a documentation aid. Subroutine lines must appear after the total calculation specifications. The operation codes BEGSR and ENDSR serve as delimiters
for a subroutine.
AND/OR Lines Identifier
Positions 7 and 8 can contain AN or OR to define additional indicators (positions 9
through 11) for a calculation.
The entry in positions 7 and 8 of the line immediately preceding an AND/OR line or
a group of AND/OR lines determines when the calculation is to be processed. The
entry in positions 7 and 8 on the first line of a group applies to all AND/OR lines in
Chapter 17. Calculation Specifications
327
Calculation Specification Statement
the group. A control level indicator (L1 through L9, L0, or LR) is entered for total
calculations, an SR or blanks for subroutines, and a blank for detail calculations.
Positions 9-11 (Indicators)
Entry
Explanation
Blank
The operation is processed on every record
01-99
General indicators.
KA-KN, KP-KY
Function key indicators.
L1-L9
Control level indicators.
LR
Last record indicator.
MR
Matching record indicator.
H1-H9
Halt indicators.
RT
Return indicator.
U1-U8
External indicators.
OA-OG, OV
Overflow indicator.
Positions 10 and 11 contain an indicator that is tested to determine if a particular
calculation is to be processed. A blank in position 9 designates that the indicator
must be on for a calculation to be done. An N in positions 9 designates that the
associated indicator must be off for a calculation to be done.
Positions 12-25 (Factor 1)
Factor 1 names a field or gives actual data (literals) on which an operation is done,
or contains a RPG IV special word (for example, *LOCK) which provides extra
information on how an operation is to be done. The entry must begin in position 12.
The entries that are valid for factor 1 depend on the operation code specified in
positions 26 through 35. For the specific entries for factor 1 for a particular operation code, see Chapter 22, “Operation Codes” on page 427. With some operation
codes, two operands may be specified separated by a colon.
Positions 26-35 (Operation and Extender)
Positions 26 through 35 specify the kind of operation to be done using factor 1,
factor 2, and the result field entries. The operation code must begin in position 26.
For further information on the operation codes, see Chapter 22, “Operation Codes”
on page 427.
Operation Extender
Entry
Explanation
Blank
No operation extension supplied
H
Half adjust (round) result of numeric operation
N
Record is read but not locked
Set pointer to *NULL after successful DEALLOC
P
328
ILE RPG for AS/400 Reference
Pad the result field with blanks
Calculation Specification Statement
D
Pass operational descriptors on bound call
Date field
T
Time field
Z
Timestamp field
M
Default precision rules
R
"Result Decimal Position" precision rules
E
Error handling
The operation extenders provide additional attributes to the operations that they
accompany. Operation extenders are specified in positions 26-35 of calculation
specifications. They must begin to the right of the operation code and be contained
within parentheses; blanks can be used for readability. For example, the following
are all valid entries: MULT(H), MULT (H), MULT ( H ).
More than one operation extender can be specified. For example, the CALLP operation can specify both error handling and the default precision rules with
CALLP(EM).
An H indicates whether the contents of the result field are to be half adjusted
(rounded). Resulting indicators are set according to the value of the result field after
half-adjusting has been done.
An N in a READ, READE, READP, READPE, or CHAIN operation on an update
disk file indicates that a record is to be read, but not locked. If no value is specified,
the default action of locking occurs.
An N in a DEALLOC operation indicates that the result field pointer is to be set to
*NULL after a successful deallocation.
A P indicates that, the result field is padded after executing the instruction if the
result field is longer than the result of the operation.
A D when specified on the CALLB operation code indicates that operational
descriptors are included.
The D, T, and Z extenders can be used with the TEST operation code to indicate a
date, time, or timestamp field.
M and R are specified for the precision of single free-form expressions. For more
information, see “Precision Rules for Numeric Operations” on page 419.
An M indicates that the default precision rules are used.
An R indicates that the precision of a decimal intermediate will be computed such
that the number of decimal places will never be reduced smaller than the number of
decimal positions of the result of the assignment.
An E indicates that operation-related errors will be checked with built-in function
%ERROR.
Chapter 17. Calculation Specifications
329
Calculation Specification Statement
Positions 36-49 (Factor 2)
Factor 2 names a field, record format or file, or gives actual data on which an operation is to be done, or contains a special word (for example, *ALL) which gives
extra information about the operation to be done. The entry must begin in position
36. The entries that are valid for factor 2 depend on the operation code specified in
positions 26 through 35. With some operation codes, two operands may be specified separated by a colon. For the specific entries for factor 2 for a particular operation code, see Chapter 22, “Operation Codes” on page 427.
Positions 50-63 (Result Field)
The result field names the field or record format that contains the result of the calculation operation specified in positions 26 through 35. The field specified must be
modifiable. For example, it cannot be a lookahead field or a user date field. With
some operation codes, two operands may be specified separated by a colon. See
Chapter 22, “Operation Codes” on page 427 for the result field rules for individual
operation codes.
Positions 64-68 (Field Length)
|
Entry
Explanation
1-30
Numeric field length.
1-65535
Character field length.
Blank
The result field is defined elsewhere or a field cannot be defined using
this operation code
Positions 64 through 68 specify the length of the result field. This entry is optional,
but can be used to define a numeric or character field not defined elsewhere in the
program. These definitions of the field entries are allowed if the result field contains
a field name. Other data types must be defined on the definition specification or on
the calculation specification using the *LIKE DEFINE operation.
The entry specifies the number of positions to be reserved for the result field. The
entry must be right-adjusted. The unpacked length (number of digits) must be specified for numeric fields.
If the result field is defined elsewhere in the program, no entry is required for the
length. However, if the length is specified, and if the result field is defined elsewhere, the length must be the same as the previously defined length.
Positions 69-70 (Decimal Positions)
Entry
Explanation
Blank
The result field is character data, has been defined elsewhere in the
program, or no field name has been specified.
0-30
Number of decimal positions in a numeric result field.
Positions 69-70 indicate the number of positions to the right of the decimal in a
numeric result field. If the numeric result field contains no decimal positions, enter a
'0' (zero). This position must be blank if the result field is character data or if no
field length is specified. The number of decimal positions specified cannot exceed
the length of the field.
330
ILE RPG for AS/400 Reference
Calculation Extended Factor 2 Specification Statement
Positions 71-76 (Resulting Indicators)
These positions can be used, for example, to test the value of a result field after
the completion of an operation, or to indicate conditions like end-of-file, error, or
record-not-found. For some operations, you can control the way the operation is
performed by specifying different combinations of the three resulting indicators (for
example, LOOKUP). The resulting indicator positions have different uses,
depending on the operation code specified. See the individual operation codes in
Chapter 22, “Operation Codes” on page 427 for a description of the associated
resulting indicators. For arithmetic operations, the result field is tested only after the
field is truncated and half-adjustment is done (if specified). The setting of indicators
depends on the results of the tests specified.
Entry
Explanation
Blank
No resulting indicator specified
01-99
General indicators
KA-KN, KP-KY
Function key indicators
H1-H9
Halt indicators
L1-L9
Control level indicators
LR
Last record indicator
OA-OG, OV
Overflow indicators
U1-U8
External indicators
RT
Return indicator.
Resulting indicators cannot be used when the result field uses a non-indexed array.
If the same indicator is used as a resulting indicator on more than one calculation
specification, the most recent specification processed determines the status of that
indicator.
Remember the following points when specifying resulting indicators:
¹ When the calculation operation is done, the specified resulting indicators are
set off, and, if a condition specified by a resulting indicator is satisfied, that indicator is set on.
¹ When a control level indicator (L1 through L9) is set on, the lower level indicators are not set on.
¹ When a halt indicator (H1 through H9) is set on, the program ends abnormally
at the next *GETIN point in the cycle, or when a RETURN operation is processed, unless the halt indicator is set off before the indicator is tested.
Calculation Extended Factor 2 Specification Statement
Certain operation codes allow an expression to be used in the extended factor 2
field.
Chapter 17. Calculation Specifications
331
Calculation Extended Factor 2 Specification Statement
Positions 7-8 (Control Level)
See “Positions 7-8 (Control Level)” on page 326.
Positions 9-11 (Indicators)
See “Positions 9-11 (Indicators)” on page 328.
Positions 12-25 (Factor 1)
Factor 1 must be blank.
Positions 26-35 (Operation and Extender)
Positions 26 through 35 specify the kind of operation to be done using the
expression in the extended factor 2 field. The operation code must begin in position
26. For further information on the operation codes, see Chapter 22, “Operation
Codes” on page 427.
The program processes the operations in the order specified on the calculation
specifications form.
Operation Extender
Entry
Explanation
Blank
No operation extension supplied.
H
Half adjust (round) result of numeric operation
M
Default precision rules
R
"Result Decimal Position" precision rules
E
Error handling
Half adjust may be specified, using the H extender, on arithmetic EVAL and
RETURN operations.
The type of precision may be specified, using the M or R extender, on CALLP,
DOU, DOW, EVAL, IF, RETURN, and WHEN operations.
Error handling may be specified, using the 'E' extender, on CALLP operations.
Positions 36-80 (Extended Factor 2)
A free form syntax is used in this field. It consists of combinations of operands and
operators, and may optionally span multiple lines. If specified across multiple lines,
the continuation lines must be blank in positions 7-35.
The operations that take an extended factor 2 are:
¹ “CALLP (Call a Prototyped Procedure or Program)” on page 482
¹ “DOU (Do Until)” on page 516
¹ “DOW (Do While)” on page 519
¹ “EVAL (Evaluate expression)” on page 529
|
¹ “EVALR (Evaluate expression, right adjust)” on page 531
|
¹ “FOR (For)” on page 540
332
ILE RPG for AS/400 Reference
Calculation Extended Factor 2 Specification Statement
¹ “IF (If)” on page 546
¹ “RETURN (Return to Caller)” on page 637
¹ “WHEN (When True Then Select)” on page 681
See the specific operation codes for more information. See “Continuation Rules” on
page 225 for more information on coding continuation lines.
Chapter 17. Calculation Specifications
333
Calculation Extended Factor 2 Specification Statement
334
ILE RPG for AS/400 Reference
Output Specification Statement
Chapter 18. Output Specifications
Output specifications describe the record and the format of fields in a programdescribed output file and when the record is to be written. Output specifications are
optional for an externally described file. If NOMAIN is coded on a control specification, only exception output can be done.
Output specifications can be divided into two categories: record identification and
control (positions 7 through 51), and field description and control (positions 21
through 80). Detailed information for each category of output specifications is given
in:
¹ Entries for program-described files
¹ Entries for externally described files
Output Specification Statement
The general layout for the Output specification is as follows:
¹ the output specification type (O) is entered in position 6
¹ the non-commentary part of the specification extends from position 7 to position
80
¹ the comments section of the specification extends from position 81 to position
100
Program Described
For program described files, entries on the output specifications can be divided into
two categories:
¹ Record identification and control (positions 7 through 51)
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
OFilename++DF..N01N02N03Excnam++++B++A++Sb+Sa+.............................Comment+++++++++++++
OFilename++DAddN01N02N03Excnam++++.........................................Comment+++++++++++++
O.........And..N01N02N03Excnam++++.........................................Comment+++++++++++++
Figure 122. Program Described Record Layout
¹ Field description and control (positions 21 through 80). Each field is described
on a separate line, below its corresponding record identification entry.
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat++Comment+++++++++++++
O..............................................Constant/editword-ContinutioComment+++++++++++++
Figure 123. Program Described Field Layout
 Copyright IBM Corp. 1994, 1999
335
Record Identification and Control Entries
Externally Described
For externally described files, entries on output specifications are divided into the
following categories:
¹ Record identification and control (positions 7 through 39)
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
ORcdname+++D...N01N02N03Excnam++++.........................................Comment+++++++++++++
ORcdname+++DAddN01N02N03Excnam++++.........................................Comment+++++++++++++
O.........And..N01N02N03Excnam++++.........................................Comment+++++++++++++
Figure 124. Externally Described Record Layout
¹ Field description and control (positions 21 through 43, and 45).
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
O..............N01N02N03Field+++++++++.B...................................Comment+++++++++++++
Figure 125. Externally Described Field Layout
Program Described Files
Position 6 (Form Type)
An O must appear in position 6 to identify this line as an output specifications statement.
Record Identification and Control Entries
Entries in positions 7 through 51 identify the output records that make up the files,
provide the correct spacing on printed reports, and determine under what conditions
the records are to be written.
Positions 7-16 (File Name)
Entry
Explanation
A valid file name
Same file name that appears on the file description specifications for the
output file.
Specify the file name on the first line that defines an output record for the file. The
file name specified must be the same file name assigned to the output, update, or
combined file on the file description specifications. If records from files are interspersed on the output specifications, the file name must be specified each time the
file changes.
For files specified as output, update, combined or input with ADD, at least one
output specification is required unless an explicit file operation code with a data
structure name specified in the result field is used in the calculations. For example,
a WRITE operation does not require output specifications.
336
ILE RPG for AS/400 Reference
Record Identification and Control Entries
Positions 16-18 ( Logical Relationship)
Entry
Explanation
AND or OR
AND/OR indicates a relationship between lines of output indicators.
AND/OR lines are valid for output records, but not for fields.
Positions 16 through 18 specify AND/OR lines for output operations. To specify this
relationship, enter AND/OR in positions 16 through 18 on each additional line following the line containing the file name. At least one indicator must be specified on
each AND line. For an AND relationship and fetch overflow position 18 must be
specified on the first line only (file name line). A fetch overflow entry is required on
OR lines for record types requiring the fetch overflow routine.
Positions 7 through 15 must be blank when AND/OR is specified.
An unlimited number of AND/OR lines can be specified on the output specifications.
Position 17 (Type)
Entry
Explanation
H or D
Detail records usually contain data that comes directly from the input
record or that is the result of calculations processed at detail time.
Heading records usually contain constant identifying information such as
titles, column headings, page number, and date. No distinction is made
between heading and detail records. The H/D specifications are available to help the programmer document the program.
T
Total records usually contain data that is the end result of specific calculations on several detail records.
E
Exception records are written during calculation time. Exception records
can be specified only when the operation code EXCEPT is used. See
Chapter 22, “Operation Codes” on page 427 for further information on
the EXCEPT operation code.
Position 17 indicates the type of record to be written. Position 17 must have an
entry for every output record. Heading (H) and detail (D) lines are both processed
as detail records. No special sequence is required for coding the output records;
however, lines are handled at separate times within the program cycle based on
their record type. See Figure 5 on page 20 and Figure 6 on page 21 for more
information on when in the cycle output is performed.
Note: If NOMAIN is coded on a control specification, only exception output can be
done.
Positions 18-20 (Record Addition/Deletion)
Entry
Explanation
ADD
Add a record to the file or subfile.
DEL
Delete the last record read from the file. The deleted record cannot be
retrieved; the record is deleted from the system.
Chapter 18. Output Specifications
337
Record Identification and Control Entries
An entry of ADD is valid for input, output, or update files. DEL is valid for update
DISK files only. When ADD is specified, there must be an A in position 20 of the
corresponding file-description specification.
If positions 18-20 are blank, then for an output file, the record will be added; for an
update file, the record is updated.
The Record-Addition/Deletion entry must appear on the same line that contains the
record type (H, D, T, E) specification (position 17). If an AND/OR line is used following an ADD or DEL entry, this entry applies to the AND/OR line also.
Position 18 (Fetch Overflow/Release)
Entry
Explanation
Blank
Must be blank for all files except printer files (PRINTER specified in
positions 36 through 42 of the file description specifications). If position
18 is blank for printer files, overflow is not fetched.
F
Fetch overflow.
R
Release a device (workstation) after output.
Fetch Overflow
An F in position 18 specifies fetch overflow for the printer file defined on this line.
This file must be a printer file that has overflow lines. Fetch overflow is processed
only when an overflow occurs and when all conditions specified by the indicators in
positions 21 through 29 are satisfied. An overflow indicator cannot be specified on
the same line as fetch overflow.
If an overflow indicator has not been specified with the OFLIND keyword on the file
description specifications for a printer file, the compiler assigns one to the file. An
overflow line is generated by the compiler for the file, except when no other output
records exist for the file or when the printer uses externally described data. This
compiler-generated overflow can be fetched.
Overflow lines can be written during detail, total, or exception output time. When
the fetch overflow is specified, only overflow output associated with the file containing the processed fetch is output. The fetch overflow entry (F) is required on
each OR line for record types that require the overflow routine. The fetch overflow
routine does not automatically advance forms. For detailed information on the overflow routine see “Overflow Routine” on page 28 and Figure 7 on page 27
The form length and overflow line can be specified using the FORMLEN and
OFLIND keywords on the file description specifications, in the printer device file, or
through an OS/400 override command.
Release
After an output operation is complete, the device used in the operation is released
if you have specified an R in position 18 of the corresponding output specifications.
See the “REL (Release)” on page 629 operation for further information on releasing
devices.
338
ILE RPG for AS/400 Reference
Record Identification and Control Entries
Positions 21-29 (Output Conditioning Indicators)
Entry
Explanation
Blank
The line or field is output every time the record (heading, detail, total, or
exception) is checked for output.
01-99
A general indicator that is used as a resulting indicator, field indicator, or
record identifying indicator.
KA-KN, KP-KY
Function key indicators.
L1-L9
Control level indicators.
H1-H9
Halt indicators.
U1-U8
External indicator set before running the program or set as a result of a
calculation operation.
OA-OG, OV
Overflow indicator previously assigned to this file.
MR
Matching record indicator.
LR
Last record indicator.
RT
Return indicator.
1P
First-page indicator. Valid only on heading or detail lines.
Conditioning indicators are not required on output lines. If conditioning indicators
are not specified, the line is output every time that record is checked for output. Up
to three indicators can be entered on one specification line to control when a record
or a particular field within a record is written. The indicators that condition the
output are coded in positions 22 and 23, 25 and 26, and 28 and 29. When an N is
entered in positions 21, 24, or 27, the indicator in the associated position must be
off for the line or field to be written. Otherwise, the indicator must be on for the line
or field to be written. See “PAGE, PAGE1-PAGE7” on page 343 for information on
how output indicators affect the PAGE fields.
If more than one indicator is specified on one line, all indicators are considered to
be in an AND relationship.
If the output record must be conditioned by more than three indicators in an AND
relationship, enter the letters AND in positions 16 through 18 of the following line
and specify the additional indicators in positions 21 through 29 on that line.
For an AND relationship, fetch overflow (position 18) can only be specified on the
first line. Positions 40 through 51 (spacing and skipping) must be blank for all AND
lines.
An overflow indicator must be defined on the file description specifications with the
OFLIND keyword before it can be used as a conditioning indicator. If a line is to be
conditioned as an overflow line, the overflow indicator must appear on the main
specification line or on the OR line. If an overflow indicator is used on an AND line,
the line is not treated as an overflow line, but the overflow indicator is checked
before the line is written. In this case, the overflow indicator is treated like any other
output indicator.
Chapter 18. Output Specifications
339
Record Identification and Control Entries
If the output record is to be written when any one of two or more sets of conditions
exist (an OR relationship), enter the letters OR in positions 16-18 of the following
specification line, and specify the additional OR indicators on that line.
When an OR line is specified for a printer file, the skip and space entries (positions
40 through 51) can all be blank, in which case the space and skip entries of the
preceding line are used. If they differ from the preceding line, enter space and skip
entries on the OR line. If fetch overflow (position 18) is used, it must be specified
on each OR line.
Positions 30-39 (EXCEPT Name)
When the record type is an exception record (indicated by an E in position 17), a
name can be placed in these positions of the record line. The EXCEPT operation
can specify the name assigned to a group of the records to be output. This name is
called an EXCEPT name. An EXCEPT name must follow the rules for using symbolic names. A group of any number of output records can use the same EXCEPT
name, and the records do not have to be consecutive records.
When the EXCEPT operation is specified without an EXCEPT name, only those
exception records without an EXCEPT name are checked and written if the conditioning indicators are satisfied.
When the EXCEPT operation specifies an EXCEPT name, only the exception
records with that name are checked and written if the conditioning indicators are
satisfied.
The EXCEPT name is specified on the main record line and applies to all AND/OR
lines.
If an exception record with an EXCEPT name is conditioned by an overflow indicator, the record is written only during the overflow portion of the RPG IVcycle or
during fetch overflow. The record is not written at the time the EXCEPT operation is
processed.
An EXCEPT operation with no fields can be used to release a record lock in a file.
The UNLOCK operation can also be used for this purpose. In Figure 126, the
record lock in file RCDA is released by the EXCEPT operation. For more information, see ILE Application Development Example, SC41-5602-00.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
C*
C
KEY
CHAIN
RCDA
C
EXCEPT
RELEASE
ORcdname+++D...N01N02N03Excnam++++.......................................
O
O*
ORCDA
E
RELEASE
O*
(no fields)
Figure 126. Record Lock in File Released by EXCEPT Operation
340
ILE RPG for AS/400 Reference
Record Identification and Control Entries
Positions 40-51 (Space and Skip)
Use positions 40 through 51 to specify line spacing and skipping for a printer file.
Spacing refers to advancing one line at a time, and skipping refers to jumping from
one print line to another.
If spacing and skipping are specified for the same line, the spacing and skipping
operations are processed in the following sequence:
¹ Skip before
¹ Space before
¹ Print a line
¹ Skip after
¹ Space after.
If the PRTCTL (printer control option) keyword is not specified on the file
description specifications, an entry must be made in one of the following positions
when the device is PRINTER: 40-42 (space before), 43-45 (space after), 46-48
(skip before), or 49-51 (skip after). If a space/skip entry is left blank, the particular
function with the blank entry (such as space before or space after) does not occur.
If entries are made in positions 40-42 (space before) or in positions 46-51 (skip
before and skip after) and no entry is made in positions 43 - 45 (space after), no
space occurs after printing. When PRTCTL is specified, it is used only on records
with blanks specified in positions 40 through 51.
If a skip before or a skip after a line on a new page is specified, but the printer is
on that line, the skip does not occur.
Positions 40-42 (Space Before)
Entry
Explanation
0 or Blank
No spacing
1-255
Spacing values
Positions 43-45 (Space After)
Entry
Explanation
0 or Blank
No spacing
1-255
Spacing values
Positions 46-48 (Skip Before)
Entry
Explanation
Blank
No skipping occurs.
1-255
Skipping values
Chapter 18. Output Specifications
341
Field Description and Control Entries
Positions 49-51 (Skip After)
Entry
Explanation
1-255
Skipping values
Field Description and Control Entries
These entries determine under what conditions and in what format fields of a record
are to be written.
Each field is described on a separate line. Field description and control information
for a field begins on the line following the record identification line.
Positions 21-29 (Output Indicators)
Indicators specified on the field description lines determine whether a field is to be
included in the output record, except for PAGE reserved fields. See “PAGE,
PAGE1-PAGE7” on page 343 for information on how output indicators affect the
PAGE fields. The same types of indicators can be used to control fields as are
used to control records, see “Positions 21-29 (Output Conditioning Indicators)” on
page 339. Indicators used to condition field descriptions lines cannot be specified
in an AND/OR relationship. Conditioning indicators cannot be specified on format
name specifications (see “Positions 53-80 (Constant, Edit Word, Data Attributes,
Format Name)” on page 347) for program described WORKSTN files.
Positions 30-43 (Field Name)
In positions 30 through 43, use one of the following entries to specify each field that
is to be written out:
¹ A field name
¹ Blanks if a constant is specified in positions 53 through 80
¹ A table name, array name, or array element
¹ A named constant
¹ The RPG IV reserved words PAGE, PAGE1 through PAGE7, *PLACE, UDATE,
*DATE, UDAY, *DAY, UMONTH, *MONTH, UYEAR, *YEAR, *IN, *INxx, or
*IN(xx)
¹ A data structure name or data structure subfield name.
Note: A pointer field is not a valid output field—that is, pointer fields cannot be
written.
Field Names, Blanks, Tables and Arrays
The field names used must be defined in the program. Do not enter a field name if
a constant or edit word is used in positions 53-80. If a field name is entered in
positions 30 through 43, positions 7 through 20 must be blank.
Fields can be specified in any order because the sequence in which they appear on
the output records is determined by the entry in positions 47 through 51. If fields
overlap, the last field specified is the only field completely written.
When a non-indexed array name is specified, the entire array is written. An array
name with a constant index or variable index causes one element to be written.
342
ILE RPG for AS/400 Reference
Field Description and Control Entries
When a table name is specified, the element last found in a “LOOKUP (Look Up a
Table or Array Element)” on page 559 operation is written. The first element of a
table is written if no successful LOOKUP operation was done.
The conditions for a record and the field it contains must be satisfied before the
field is written out.
PAGE, PAGE1-PAGE7
To use automatic page numbering, code PAGE in positions 30 through 43 as the
name of the output field. Indicators specified in positions 21 through 29 condition
the resetting of the PAGE field, not whether it prints. The PAGE field is always
incremented by 1 and printed. If the conditioning indicators are met, it is reset to
zero before being incremented by 1 and printed. If page numbers are needed for
several output files (or for different numbering within one file), the entries PAGE1
through PAGE7 can be used. The PAGE fields are automatically zero-suppressed
by the Z edit code.
For more information on the PAGE reserved words, see “RPG IV Words with
Special Functions/Reserved Words” on page 5.
*PLACE
*PLACE is an RPG IV reserved word that is used to repeat data in an output
record. Fields or constants that have been specified on previous specification lines
can be repeated in the output record without having the field and end positions
named on a new specification line. When *PLACE is coded in positions 30 through
43, all data between the first position and the highest end position previously specified for a field in that output record is repeated until the end position specified in the
output record on the *PLACE specification line is reached. The end position specified on the *PLACE specification line must be at least twice the highest end position of the group of fields to be duplicated. *PLACE can be used with any type of
output. Blank after (position 45), editing (positions 44, 53 through 80), data format
(position 52), and relative end positions cannot be used with *PLACE.
User Date Reserved Words
The user date reserved words (UDATE, *DATE, UDAY, *DAY, UMONTH, *MONTH,
UYEAR, *YEAR) allow the programmer to supply a date for the program at run
time. For more information on the user date reserved words, see “Rules for User
Date” on page 7.
*IN, *INxx, *IN(xx)
The reserved words *IN, *INxx and *IN(xx) allow the programmer to refer to and
manipulate RPG IV indicators as data.
Position 44 (Edit Codes)
Entry
Explanation
Blank
No edit code is used.
1-9, A-D, J-Q, X, Y, Z
Numeric fields are zero-suppressed and punctuated according to a predefined pattern without the use of edit words.
Chapter 18. Output Specifications
343
Field Description and Control Entries
Position 44 is used to specify edit codes that suppress leading zeros in a numeric
field or to punctuate a numeric field without using an edit word. Allowable entries
are 1 through 9, A through D, J through Q, X, Y, Z, and blank.
Note: The entry must be blank if you are writing a float output field.
For more information on edit codes see Chapter 11, “Editing Numeric Fields” on
page 205.
Edit codes 5 through 9 are user-defined edit codes and are defined externally by an
OS/400 function. The edit code is determined at compilation time. Subsequent
changes to a user-defined edit code will not affect the editing by the RPG
IVcompiler unless the program is recompiled.
Position 45 (Blank After)
|
|
|
Entry
Explanation
Blank
The field is not reset.
B
The field specified in positions 30 through 43 is reset to blank, zero, or
the default date/time/timestamp value after the output operation is complete.
Position 45 is used to reset a numeric field to zeros or a character, graphic, or
UCS-2 field to blanks. Date, time, and timestamp fields are reset to their default
values.
If the field is conditioned by indicators in positions 21 through 29, the blank after is
also conditioned. This position must be blank for look-ahead, user date reserved
words, *PLACE, named constants, and literals.
Resetting fields to zeros may be useful in total output when totals are accumulated
and written for each control group in a program. After the total is accumulated and
written for one control group, the total field can be reset to zeros before accumulation begins on the total for the next control group.
If blank after (position 45) is specified for a field to be written more than once, the B
should be entered on the last line specifying output for that field, or else the field
named will be printed as the blank-after value for all lines after the one doing the
blank after.
Positions 47-51 (End Position)
Entry
Explanation
1-n
End position
K1-K10
Length of format name for WORKSTN file.
Positions 47 through 51 define the end position of a field or constant on the output
record, or define the length of the data description specifications record format
name for a program described WORKSTN file.
The K identifies the entry as a length rather than an end position, and the number
following the K indicates the length of the record format name. For example, if the
format name is CUSPMT, the entry in positions 50 and 51 is K6. Leading zeros
are permitted following the K, and the entry must be right-adjusted.
344
ILE RPG for AS/400 Reference
Field Description and Control Entries
Valid entries for end positions are blanks, +nnnn, −nnnn, and nnnnn. All entries in
these positions must end in position 51. Enter the position of the rightmost character of the field or constant. The end position must not exceed the record length
for the file.
If an entire array is to be written, enter the end position of the last element in the
array in positions 47 through 51. If the array is to be edited, be careful when specifying the end position to allow enough positions to write all edited elements. Each
element is edited according to the edit code or edit word.
The +nnnn or −nnnn entry specifies the placement of the field or constant relative
to the end position of the previous field. The number (nnnn) must be right-adjusted,
but leading zeros are not required. Enter the sign anywhere to the left of the
number within the entry field. To calculate the end position, use these formulas:
EP = PEP +nnnn + FL
EP = PEP −nnnn + FL
EP is the calculated end position. PEP is the previous end position. For the first
field specification in the record, PEP is equal to zero. FL is the length of the field
after editing, or the length of the constant specified in this specification. The use of
+nnnn is equivalent to placing nnnn positions between the fields. A -nnnn causes
an overlap of the fields by nnnn positions. For example, if the previous end position
(PEP) is 6, the number of positions to be placed between the fields (nnnn) is 5, and
the field length (FL) is 10, the end position (EP) equals 21.
When *PLACE is used, an actual end position must be specified; it cannot be blank
or a displacement.
An entry of blank is treated as an entry of +0000. No positions separate the fields.
Position 52 (Data Format)
Entry
Explanation
Blank
¹ For numeric fields the data is to be written in zoned decimal format.
¹ For float numeric fields, the data is to be written in the external
display representation.
¹ For graphic fields, the data is to be written with SO/SI brackets.
¹ For UCS-2 fields, the data is to be written in UCS-2 format.
|
¹ For date, time, and timestamp fields the data is to be written without
format conversion performed.
¹ For character fields, the data is to be written as it is stored.
|
|
A
The character field is to be written in either fixed- or variable-length
format depending on the absense or presence of the *VAR data attribute.
C
The UCS-2 field is to be written in either fixed- or variable-length format
depending on the absense or presence of the *VAR data attribute.
G
The graphic field (without SO/SI brackets) will be written in either fixedor variable-length format depending on the absense or presence of the
*VAR data attribute.
Chapter 18. Output Specifications
345
Field Description and Control Entries
B
The numeric field is to be written in binary format.
F
The numeric field is to be written in float format.
I
The numeric field is to be written out in integer format.
L
The numeric field is to be written with a preceding (left) plus or minus
sign, in zoned-decimal format.
N
The character field is to be written in indicator format.
P
The numeric field is to be written in packed-decimal format.
R
The numeric field is to be written with a following (right) plus or minus
sign, in zoned-decimal format.
S
The numeric field is to be written out in zoned-decimal format.
U
The numeric field is to be written out in unsigned integer format.
D
Date field— the date field will be converted to the format specified in
positions 53-80 or to the default file date format.
T
Time field— the time field will be converted to the format specified in
positions 53-80 or to the default file time format.
Z
Valid for Timestamp fields only.
This position must be blank if editing is specified.
The entry in position 52 specifies the external format of the data in the records in
the file. This entry has no effect on the format used for internal processing of the
output field in the program.
For numeric fields, the number of bytes required in the output record depends on
this format. For example, a numeric field with 5 digits requires:
¹ 5 bytes when written in zoned format
¹ 3 bytes when written in packed format
¹ 6 bytes when written in either L or R format
¹ 4 bytes when written in binary format
¹ 2 bytes when written in either I or U format. This may cause an error at run
time if the value is larger than the maximum value for a 2-byte integer or
unsigned field. For the case of 5-digit fields, binary format may be better.
Float numeric fields written out with blank Data Format entry occupy either 14
or 23 positions (for 4-byte and 8-byte float fields respectively) in the output
record.
A 'G' or blank must be specified for a graphic field in a program-described file. If 'G'
is specified, then, the data will be output without SO/SI. If this column is blank for
program-described output, then SO/SI brackets will be placed around the field in
the output record by the compiler if the field is of type graphic. You must ensure
that there is sufficient room in the output record for both the data and the SO/SI
characters.
346
ILE RPG for AS/400 Reference
Field Description and Control Entries
Positions 53-80 (Constant, Edit Word, Data Attributes, Format Name)
Positions 53 through 80 are used to specify a constant, an edit word, a data attribute, or a format name for a program described file.
Constants
Constants consist of character data (literals) that does not change from one processing of the program to the next. A constant is the actual data used in the output
record rather than a name representing the location of the data.
A constant can be placed in positions 53 through 80. The constant must begin in
position 54 (apostrophe in position 53), and it must end with an apostrophe even if
it contains only numeric characters. Any apostrophe used within the constant must
be entered twice; however, only one apostrophe appears when the constant is
written out. The field name (positions 30 through 43) must be blank. Constants can
be continued (see “Continuation Rules” on page 225 for continuation rules). Instead
of entering a constant, you can use a named constant.
|
Graphic and UCS-2 literals or named constants are not allowed as edit words, but
may be specified as constants.
Edit Words
An edit word specifies the punctuation of numeric fields, including the printing of
dollar signs, commas, periods, and sign status. See “Parts of an Edit Word” on
page 213 for details.
|
Edit words must be character literals or named constants. Graphic, UCS-2, or
hexadecimal literals and named constants are not allowed.
Data Attributes
|
|
Data attributes specify the external format for a date, time, or variable-length character, graphic, or UCS-2 field.
For date and time data, if no date or time format is specified, then the
format/separator specified for the file (with either DATFMT or TIMFMT or both) is
used. If there is no external date or time format specified for the file, then an error
message is issued. See Table 13 on page 186 and Table 16 on page 189 for
valid date and time formats.
|
|
For character, graphic, and UCS-2 data, the *VAR data attribute is used to specify
variable-length output fields. If this entry is blank for character, graphic, and UCS-2
data, then the external format is fixed length. For more information on variablelength fields, see “Variable-Length Character, Graphic and UCS-2 Formats” on
page 165.
Note: The number of bytes occupied in the output record depends on the format
specified. For example, a date written in *MDY format requires 8 bytes, but
a date written in *ISO format requires 10 bytes.
For more information on external formats, see “Internal and External Formats” on
page 159.
Chapter 18. Output Specifications
347
Record Identification and Control Entries
Record Format Name
The name of the data description specifications record format that is used by a
program described WORKSTN file must be specified in positions 53 through 62.
One format name is required for each output record for the WORKSTN file; specifying more than one format name per record is not allowed. Conditioning indicators
cannot be specified on format name specifications for program described
WORKSTN files. The format name must be enclosed in apostrophes. You must
also enter Kn in positions 47 through 51, where n is the length of the format name.
For example, if the format name is ‘CUSPMT’, enter K6 in positions 50 and 51. A
named constant can also be used.
Externally Described Files
Position 6 (Form Type)
An O must appear in position 6 to identify this line as an output specifications statement.
Record Identification and Control Entries
Output specifications for an externally described file are optional. Entries in positions 7 through 39 of the record identification line identify the record format and
determine under what conditions the records are to be written.
Positions 7-16 (Record Name)
Entry
Explanation
A valid record format name
A record format name must be specified for an externally described file.
Positions 16-18 (Logical Relationship)
Entry
Explanation
AND or OR
AND/OR indicates a relationship between lines of output indicators.
AND/OR lines are valid for output records, but not for fields.
See “Positions 16-18 ( Logical Relationship)” on page 337 for more information.
Position 17 (Type)
Entry
Explanation
H or D
Detail records
T
Total records
E
Exception records.
Position 17 indicates the type of record to be written. See “Position 17 (Type)” on
page 337 for more information.
348
ILE RPG for AS/400 Reference
Field Description and Control Entries
Position 18 (Release)
Entry
Explanation
R
Release a device after output.
See “Release” on page 338 for more information.
Positions 18-20 (Record Addition)
Entry
Explanation
ADD
Add a record to a file.
DEL
Delete an existing record from the file.
For more information on record addition, see “Positions 18-20 (Record
Addition/Deletion)” on page 337.
Positions 21-29 (Output Indicators)
Output indicators for externally described files are specified in the same way as
those for program described files. The overflow indicators OA-OG, OV are not valid
for externally described files. For more information on output indicators, see “Positions 21-29 (Output Conditioning Indicators)” on page 339.
Positions 30-39 (EXCEPT Name)
An EXCEPT name can be specified in these positions for an exception record line.
See “Positions 30-39 (EXCEPT Name)” on page 340 for more information.
Field Description and Control Entries
For externally described files, the only valid field descriptions are output indicators
(positions 21 through 29), field name (positions 30 through 43), and blank after
(position 45).
Positions 21-29 (Output Indicators)
Indicators specified on the field description lines determine whether a field is to be
included in the output record. The same types of indicators can be used to control
fields as are used to control records. See “Positions 21-29 (Output Conditioning
Indicators)” on page 339 for more information.
Positions 30-43 (Field Name)
Entry
Explanation
Valid field name
A field name specified for an externally described file must be present in
the external description unless the external name was renamed for the
program.
*ALL
Specifies the inclusion of all the fields in the record.
For externally described files, only the fields specified are placed in the output
record. *ALL can be specified to include all the fields in the record. If *ALL is specified, no other field description lines can be specified for that record. In particular,
you cannot specify a B (blank after) in position 45.
Chapter 18. Output Specifications
349
Field Description and Control Entries
For an update record, only those fields specified in the output field specifications
and meeting the conditions specified by the output indicators are placed in the
output record to be rewritten. The values that were read are used to rewrite all
other fields.
For the creation of a new record (ADD specified in positions 18-20), the fields specified are placed in the output record. Those fields not specified or not meeting the
conditions specified by the output indicators are written as zeros or blanks,
depending on the data format specified in the external description.
Position 45 (Blank After)
|
|
|
Entry
Explanation
Blank
The field is not reset.
B
The field specified in positions 30 through 43 is reset to blank, zero, or
the default date/time/timestamp value after the output operation is complete.
Position 45 is used to reset a numeric field to zeros or a character, graphic, or
UCS-2 field to blanks. Date, time, and timestamp fields are reset to their default
values.
If the field is conditioned by indicators in positions 21 through 29, the blank after is
also conditioned. This position must be blank for look-ahead, user date reserved
words, *PLACE, named constants, and literals.
Resetting fields to zeros may be useful in total output when totals are accumulated
and written for each control group in a program. After the total is accumulated and
written for one control group, the total field can be reset to zeros before accumulation begins on the total for the next control group.
If blank after (position 45) is specified for a field to be written more than once, the B
should be entered on the last line specifying output for that field, or else the field
named will be printed as the blank-after value for all lines after the one doing the
blank after.
350
ILE RPG for AS/400 Reference
Procedure Specification Statement
Chapter 19. Procedure Specifications
Procedure specifications are used to define prototyped procedures that are specified after the main source section, otherwise known as subprocedures.
The prototype for the subprocedure must be defined in the main source section of
the module containing the subprocedure definition. A subprocedure includes the
following:
1. A Begin-Procedure specification (B in position 24 of a procedure specification)
2. A Procedure-Interface definition, which specifies the return value and parameters, if any. The procedure-interface definition is optional if the subprocedure
does not return a value and does not have any parameters that are passed to
it. The procedure interface must match the corresponding prototype.
3. Other definition specifications of variables, constants and prototypes needed by
the subprocedure. These definitions are local definitions.
4. Any calculation specifications needed to perform the task of the procedure. Any
subroutines included within the subprocedure are local. They cannot be used
outside of the subprocedure. If the subprocedure returns a value, then a
RETURN operation must be coded within the subprocedure. You should ensure
that a RETURN operation is performed before reaching the end of the procedure.
5. An End-Procedure specification (E in position 24 of a procedure specification)
Except for a procedure-interface definition, which may be placed anywhere within
the definition specifications, a subprocedure must be coded in the order shown
above.
For an example of a subprocedure, see “Subprocedure Definition” on page 91.
Procedure Specification Statement
The general layout for the procedure specification is as follows:
¹ The procedure specification type (P) is entered in position 6
¹ The non-commentary part of the specification extends from position 7 to position 80
– The fixed-format entries extend from positions 7 to 24
– The keyword entries extend from positions 44 to 80
¹ The comments section of the specification extends from position 81 to position
100
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
PName+++++++++++..B...................Keywords+++++++++++++++++++++++++++++Comments++++++++++++
Figure 127. Procedure Specification Layout
 Copyright IBM Corp. 1994, 1999
351
Procedure Specification Statement
Procedure Specification Keyword Continuation Line
If additional space is required for keywords, the keywords field can be continued on
subsequent lines as follows:
¹ Position 6 of the continuation line must contain a P
¹ Positions 7 to 43 of the continuation line must be blank
¹ The specification continues on or past position 44
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
P.....................................Keywords+++++++++++++++++++++++++++++Comments++++++++++++
Figure 128. Procedure Specification Keyword Continuation Line Layout
Procedure Specification Continued Name Line
A name that is up to 15 characters long can be specified in the Name entry of the
procedure specification without requiring continuation. Any name (even one with 15
characters or fewer) can be continued on multiple lines by coding an ellipsis (...) at
the end of the partial name. A name definition consists of the following parts:
1. Zero or more continued name lines. Continued name lines are identified as
having an ellipsis as the last non-blank character in the entry. The name must
begin within positions 7 to 21 and may end anywhere up to position 77 (with an
ellipsis ending in position 80). There cannot be blanks between the start of the
name and the ellipsis character. If any of these conditions is not true, the line is
parsed as a main procedure-name line.
2. One main procedure-name line, containing a name, begin/end procedure, and
keywords. If a continued name line is coded, the Name entry of the main
procedure-name line may be left blank.
3. Zero or more keyword continuation lines.
*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8 ...+... 9 ...+... 10
PContinuedName+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Comments++++++++++++
Figure 129. Procedure Specification Continued Name Line Layout
Position 6 (Form Type)
Enter a P in this position for a procedure specification.
Positions 7-21 (Name)
Entry
Explanation
Name
The name of the subprocedure to be defined.
Use positions 7-21 to specify the name of the subprocedure being defined. If the
name is longer than 15 characters, a name is specified in positions 7 - 80 of the
continued name lines. The normal rules for RPG IV symbolic names apply;
reserved words cannot be used (see “Symbolic Names” on page 3). The name can
begin in any position in the space provided.
352
ILE RPG for AS/400 Reference
Procedure-Specification Keywords
The name specified must be the same as the name of the prototype describing the
procedure. If position 24 contains an E, then the name is optional.
Position 24 (Begin/End Procedure)
Entry
Explanation
B
The specification marks the beginning of the subprocedure being
defined.
E
The specification marks the end of the subprocedure being defined.
A subprocedure coding consists minimally of a beginning procedure specification
and an ending procedure specification. Any parameters and return value, as well as
other definitions and calculations for the subprocedure are specified between the
procedure specifications.
Positions 44-80 (Keywords)
Positions 44 to 80 are provided for procedure specification keywords. Only a BeginProcedure specification (B in position 24) can have a keyword entry.
Procedure-Specification Keywords
EXPORT
The specification of the EXPORT keyword allows the procedure to be called by
another module in the program. The name in positions 7-21 is exported in uppercase form.
|
|
|
|
Note: Procedure names are not imported using the IMPORT keyword. They are
imported implicitly by any module in the program that makes a bound call to
the procedure or that uses the procedure name to initialize a procedure
pointer.
If the EXPORT keyword is not specified, the procedure can only be called from
within the module.
Chapter 19. Procedure Specifications
353
Procedure-Specification Keywords
354
ILE RPG for AS/400 Reference
Built-in Functions, Expressions, and Operation Codes
This section describes the various ways in which you can manipulate data or
devices. The major topics include:
¹ Built-in functions and their use on definition specifications and calculation specifications.
¹ Expressions and the rules governing them.
¹ Operation codes grouped functionally and common information within those
groups.
¹ Operation codes in detail in alphabetical order.
 Copyright IBM Corp. 1994, 1999
355
356
ILE RPG for AS/400 Reference
Chapter 20. Built-in Functions
Built-in functions are similar to operation codes in that they perform operations on
data you specify. 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.
C*L0N01Factor1+++++++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))
Figure 130. Built-in Function Arguments Example
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.
 Copyright IBM Corp. 1994, 1999
357
C*L0N01Factor1+++++++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
Figure 131. Built-in Function Example
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.
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))
Figure 132. Simplified Maintenance with Built-in Functions
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
358
ILE RPG for AS/400 Reference
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 31 (Page 1 of 3). Built-In Functions
|
|
|
Built-in Function Name
Argument(s)
Value Returned
%ABS
numeric expression
absolute value of expression
%ADDR
variable name
address of variable
%CHAR
graphic, UCS-2, numeric, date,
time, or timestamp expression
value in character format
%DEC
numeric expression
{:digits:decpos}
value in packed numeric format
%DECH
numeric expression
:digits:decpos
half-adjusted value in packed
numeric format
%DECPOS
numeric expression
number of decimal digits
%DIV
dividend: divisor
the quotient from the division of
the two arguments
%EDITC
non-float numeric expression:edit
code {:*CURSYM | *ASTFILL |
currency symbol}
string representing edited value
%EDITFLT
numeric expression
character external display representation of float
%EDITW
non-float numeric expression:edit
word
string representing edited value
%ELEM
array, table, or multiple occurrence data structure name
number of elements or occurrences
%EOF
{file name}
'1' if the most recent file input
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
%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
%FLOAT
numeric expression
value in float format
Chapter 20. Built-in Functions
359
Table 31 (Page 2 of 3). Built-In Functions
Built-in Function Name
Argument(s)
Value Returned
%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
|
|
%GRAPH
character, graphic, or UCS-2
expression
value in graphic format
%INT
numeric expression
value in integer format
%INTH
numeric expression
half-adjusted value in integer
format
%LEN
any expression
length in digits or characters
%NULLIND
null-capable field name
value in indicator format representing the null indicator setting
for the null-capable field
%OPEN
file name
'1' if the specified file is open
'0' if the specified file is closed
|
|
%PADDR
procedure name
address of procedure
%PARMS
none
number of parameters passed to
procedure
%REM
dividend: divisor
the remainder from the division
of the two arguments
%REPLACE
replacement 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
%SCAN
search argument:string to be
searched{:start position}
first position of search argument
in string or zero if not found
%SIZE
variable, array, or literal {:* ALL}
size of variable or literal
%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
360
%STR
pointer{:maximum length}
characters addressed by pointer
argument up to but not including
the first x'00'
%SUBST
string:start{:length}
substring
ILE RPG for AS/400 Reference
Table 31 (Page 3 of 3). Built-In Functions
|
|
|
Built-in Function Name
Argument(s)
Value Returned
%TRIM
string
string with left and right blanks
trimmed
%TRIML
string
string with left blanks trimmed
%TRIMR
string
string with right blanks trimmed
%UCS2
character, graphic, or UCS-2
expression
value in UCS-2 format
%UNS
numeric expression
value in unsigned format
%UNSH
numeric expression
half-adjusted value in unsigned
format
%XFOOT
array expression
sum of the elements
For more information on using built-in functions, see:
¹ Chapter 15, “Definition Specifications” on page 273
¹ “Calculation Extended Factor 2 Specification Statement” on page 331
¹ Chapter 21, “Expressions” on page 411
¹ “DOU (Do Until)” on page 516
¹ “DOW (Do While)” on page 519
¹ “EVAL (Evaluate expression)” on page 529
|
¹ “EVALR (Evaluate expression, right adjust)” on page 531
|
¹ “FOR (For)” on page 540
¹ “IF (If)” on page 546
¹ “RETURN (Return to Caller)” on page 637
¹ “WHEN (When True Then Select)” on page 681
Chapter 20. Built-in Functions
361
Built-in Functions Alphabetically
Built-in Functions Alphabetically
%ABS (Absolute Value of Expression)
%ABS(numeric expression)
%ABS returns the absolute value of the numeric expression specified as the
parameter. If the value of the numeric expression is non-negative, the value is
returned unchanged. If the value is negative, the value returned is the value of the
expression but with the negative sign removed.
%ABS may be used either in expressions or as parameters to keywords. When
used with keywords, the operand must be a numeric literal, a constant name
representing a numeric value, or a built-in function with a numeric value known at
compile-time.
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D f8
s
8f
inz (-1)
D i10
s
10i 0 inz (-123)
D p7
s
7p 3 inz (-1234.567)
CL0N01Factor1+++++++Opcode&ExtExtended-factor2+++++++++++++++++++++++++++
C
eval
f8 = %abs (f8)
C
eval
i10 = %abs (i10 - 321)
C
eval
p7 = %abs (p7)
* The value of "f8" is now 1.
* The value of "i10" is now 444.
* The value of "p7" is now 1234.567.
Figure 133. %ABS Example
362
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%ADDR (Get Address of Variable)
%ADDR(variable)
%ADDR(variable(index))
%ADDR(variable(expression))
%ADDR returns a value of type basing pointer. The value is the address of the
specified variable. It may only be compared with and assigned to items of type
basing pointer.
If %ADDR with an array index parameter is specified as parameter for definition
specification keywords INZ or CONST, the array index must be known at compiletime. The index must be either a numeric literal or a numeric constant.
In an EVAL operation where the result of the assignment is an array with no index,
%ADDR on the right hand side of the assignment operator has a different meaning
depending on the argument for the %ADDR. If the argument for %ADDR is an
array name without an index and the result is an array name, each element of the
result array will contain the address of the beginning of the argument array. If the
argument for %ADDR is an array name with an index of (*), then each element of
the result array will contain the address of the corresponding element in the argument array. This is illustrated in Figure 134 on page 364.
If the variable specified as parameter is a table, multiple occurrence data structure,
or subfield of a multiple occurrence data structure, the address will be the address
of the current table index or occurrence number.
If the variable is based, %ADDR returns the value of the basing pointer for the
variable. If the variable is a subfield of a based data structure, the value of %ADDR
is the value of the basing pointer plus the offset of the subfield.
If the variable is specified as a PARM of the *ENTRY PLIST, %ADDR returns the
address passed to the program by the caller.
Chapter 20. Built-in Functions
363
Built-in Functions Alphabetically
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
*
* The following set of definitions is valid since the array
* index has a compile-time value
*
D
ARRAY
S
20A
DIM (100)
* Set the pointer to the address of the seventh element of the array.
D
PTR
S
*
INZ (%ADDR(ARRAY(SEVEN)))
D
SEVEN
C
CONST (7)
*
D DS1
DS
OCCURS (100)
D
20A
D
SUBF
10A
D
30A
D CHAR10
S
10A
BASED (P)
D PARRAY
S
*
DIM(100)
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
*
C
23
OCCUR
DS1
C
EVAL
SUBF = *ALL'abcd'
C
EVAL
P = %ADDR (SUBF)
C
IF
CHAR10 = SUBF
*
This condition is true
C
ENDIF
C
IF
%ADDR (CHAR10) = %ADDR (SUBF)
*
This condition is also true
C
ENDIF
* The following statement also changes the value of SUBF
C
EVAL
CHAR10 = *ALL'efgh'
C
IF
CHAR10 = SUBF
*
This condition is still true
C
ENDIF
*-------------------------------------------------------------C
24
OCCUR
DS1
C
IF
CHAR10 = SUBF
*
This condition is no longer true
C
ENDIF
*-------------------------------------------------------------* The address of an array element is taken using an expression
* as the array index
*
C
EVAL
P = %ADDR (ARRAY (X + 10))
*-------------------------------------------------------------* Each element of the array PARRAY contains the address of the
* first element of the array ARRAY.
C
EVAL
PARRAY = %ADDR(ARRAY)
* Each element of the array PARRAY contains the address of the
* corresponding element of the array ARRAY
C
EVAL
PARRAY = %ADDR(ARRAY(*))
Figure 134. %ADDR Example
364
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%CHAR (Convert to Character Data)
%CHAR(expression)
|
%CHAR converts the value of the expression from graphic, UCS-2, numeric, date,
time or timestamp data to type character. The converted value remains unchanged,
but is returned in a format that is compatible with character data.
|
If the parameter is a constant, the conversion will be done at compile time.
|
|
|
If a UCS-2 conversion results in substitution characters, a warning message will be
given in the compiler listing if the parameter is a constant. Otherwise, status 00050
will be set at run time but no error message will be given.
For graphic data, the value returned includes the shift-in and shift-out characters.
For example, if a 5 character graphic field is coverted, the returned value is 12
characters (10 bytes of graphic data plus the two shift characters). If the value of
the expression has a variable length, the value returned is in varying format.
|
|
For date, time, or timestamp data, the returned value includes any separator characters. The format and separators of the result are the same as that of the parameter.
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D ChineseName
S
20G
VARYING INZ(G'oXXYYZZi')
D date
S
D
INZ(D'1997/02/03')
D time
S
T
INZ(T'12:23:34')
D result
S
100A
VARYING
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
C
EVAL
result = 'It is ' + %CHAR(time)
C
+ ' on ' + %CHAR(date)
* result = 'It is 12:23:34 on 1997/02/03'
*
C
EVAL
result = 'The time is now '
C
+ %SUBST(%CHAR(time):1:5) + '.'
* result = 'The time is now 12:23.'
*
C
EVAL
result = 'The customer''s name is '
C
+ %CHAR(ChineseName) + '.'
* result = 'The customer's name is oXXYYZZi.'
Figure 135. %CHAR Example
Chapter 20. Built-in Functions
365
Built-in Functions Alphabetically
%DEC (Convert to Packed Decimal Format)
%DEC(numeric expression{:precision:decimal places})
%DEC converts the value of the numeric expression to decimal (packed) format
with precision digits and decimal places decimal positions. The precision and
decimal places must be numeric literals, named constants that represent numeric
literals, or built-in functions with a numeric value known at compile-time.
Parameters precision and decimal places may be omitted if the type of numeric
expression is not float. If these parameters are omitted, the precision and decimal
places are taken from the attributes of numeric expression.
%DECH (Convert to Packed Decimal Format with Half Adjust)
%DECH(numeric expression :precision:decimal places )
%DECH is the same as %DEC except that if numeric expression is a decimal or
float value, half adjust is applied to the value of numeric expression when converting to the desired precision. No message is issued if half adjust cannot be performed.
Unlike, %DEC, all three parameters are required.
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D p7
s
7p 3 inz (1234.567)
D s9
s
9s 5 inz (73.73442)
D f8
s
8f
inz (123.456789)
D result1
s
15p 5
D result2
s
15p 5
D result3
s
15p 5
CL0N01Factor1+++++++Opcode&ExtExtended-factor2+++++++++++++++++++++++++++
C
eval
result1 = %dec (p7) + 0.011
C
eval
result2 = %dec (s9 : 5: 0)
C
eval
result3 = %dech (f8: 5: 2)
* The value of "result1" is now 1234.57800.
* The value of "result2" is now
73.00000
* The value of "result3" is now 123.46000.
Figure 136. %DEC and %DECH Example
366
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%DECPOS (Get Number of Decimal Positions)
%DECPOS(numeric expression)
%DECPOS returns the number of decimal positions of the numeric variable or
expression. The value returned is a constant, and so may participate in constant
folding.
The numeric expression must not be a float variable or expression.
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D p7
s
7p 3 inz (8236.567)
D s9
s
9s 5 inz (23.73442)
D result1
s
5i 0
D result2
s
5i 0
D result3
s
5i 0
CL0N01Factor1+++++++Opcode&ExtExtended-factor2+++++++++++++++++++++++++++
C
eval
result1 = %decpos (p7)
C
eval
result2 = %decpos (s9)
C
eval
result3 = %decpos (p7 * s9)
* The value of "result1" is now 3.
* The value of "result2" is now 5.
* The value of "result3" is now 8.
Figure 137. %DECPOS Example
See Figure 154 on page 387 for an example of %DECPOS with %LEN.
Chapter 20. Built-in Functions
367
Built-in Functions Alphabetically
|
|
%DIV (Return Integer Portion of Quotient)
%DIV(n:m)
|
|
|
|
|
|
%DIV returns the integer portion of the quotient that results from dividing operands
n by m. The two operands must be numeric values with zero decimal positions. If
either operand is a packed, zoned, or binary numeric value, the result is packed
numeric. If either operand is an integer numeric value, the result is integer. Otherwise, the result is unsigned numeric. Float numeric operands are not allowed. (See
also “%REM (Return Integer Remainder)” on page 393.)
|
|
|
If the operands are constants that can fit in 8-byte integer or unsigned fields, constant folding is applied to the built-in function. In this case, the %DIV built-in function can be coded in the definition specifications.
|
This function is illustrated in Figure 159 on page 393.
368
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%EDITC (Edit Value Using an Editcode)
%EDITC(numeric : editcode {: *ASTFILL | *CURSYM | currency-symbol})
This function returns a character result representing the numeric value edited
according to the edit code. In general, the rules for the numeric value and edit code
are identical to those for editing numeric values in output specifications. The third
parameter is optional, and if specified, must be one of:
|
*ASTFILL Indicates that asterisk protection is to be used. This means that leading
zeros are replaced with asterisks in the returned value. For example,
%EDITC(-0012.5 : 'K' : *ASTFILL) returns '***12.5-'.
*CURSYM
|
Indicates that a floating currency symbol is to be used. The actual
symbol will be the one specified on the control specification in the
CURSYM keyword, or the default, '$'. When *CURSYM is specified, the
currency symbol is placed in the the result just before the first significant
digit. For example, %EDITC(0012.5 : 'K' : *CURSYM) returns ' $12.5 '
.
currency-symbol
Indicates that floating currency is to be used with the provided currency
symbol. It must be a 1-byte character constant (literal, named constant
or expression that can be evaluated at compile time). For example,
%EDITC(0012.5 : 'K' : 'X') returns '
X12.5 '.
|
|
|
The result of %EDITC is always the same length, and may contain leading and
trailing blanks. For example, %EDITC(NUM : 'A' : '$') might return '$1,234.56CR' for
one value of NUM and '
$4.56 ' for another value.
Float expressions are not allowed in the first parameter (you can use %DEC to
convert a float to an editable format). In the second parameter, the edit code is
specified as a character constant; supported edit codes are: 'A' - 'D', 'J' - 'Q', 'X' 'Z', '1' - '9'. The constant can be a literal, named constant or an expression whose
value can be determined at compile time.
Chapter 20. Built-in Functions
369
Built-in Functions Alphabetically
|
|
|
|
|
|
|
|
|
|
|
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D msg
S
100A
D salary
S
9P 2 INZ(1000)
* If the value of salary is 1000, then the value of salary * 12
* is 12000.00. The edited version of salary * 12 using the A edit
* code with floating currency is ' $12,000.00 '.
* The value of msg is 'The annual salary is $12,000.00'
CL0N01Factor1+++++++Opcode&ExtExtended-factor2+++++++++++++++++++++++++++
C
EVAL
msg = 'The annual salary is '
C
+ %trim(%editc(salary * 12
C
:'A': *CURSYM))
|
|
|
|
C
C
C
|
|
|
|
|
* In the next example, the value of msg is 'Salary is $*****12,000.00'
* Note that the '$' comes from the text, not from the edit code.
C
EVAL
msg = 'Salary is $'
C
+ %trim(%editc(salary * 12
C
:'B': *ASTFILL))
|
|
|
C
C
* In the next example, the value of msg is 'The annual salary is &12,000.00'
EVAL
msg = 'The annual salary is '
+ %trim(%editc(salary * 12
:'A': '&'))
* In the next example, the value of msg is 'The date is 1/14/1999'
EVAL
msg = 'The date is '
+ %trim(%editc(*date : 'Y'))
|
Figure 138. %EDITC Example 1
A common requirement is to edit a field as follows:
¹ Leading zeros are suppressed
¹ Parentheses are placed around the value if it is negative
The following accomplishes this using an %EDITC in a subprocedure:
370
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D neg
S
5P 2
inz(-12.3)
D pos
S
5P 2
inz(54.32)
D editparens
PR
50A
D
val
30P 2
value
D editedVal
S
10A
CL0N01Factor1+++++++Opcode&ExtExtended-factor2+++++++++++++++++++++++++++
C
EVAL
editedVal = editparens(neg)
* Now editedVal has the value '(12.30)
'
C
EVAL
editedVal = editparens(pos)
* Now editedVal has the value ' 54.32
'
*--------------------------------------------------------------* Subprocedure EDITPARENS
*--------------------------------------------------------------P editparens
B
D editparens
PI
50A
D
val
30P 2
value
D lparen
S
1A
inz(' ')
D rparen
S
1A
inz(' ')
D res
S
50A
* Use parentheses if the value is negative
C
IF
val < 0
C
EVAL
lparen = '('
C
EVAL
rparen = ')'
C
ENDIF
* Return the edited value
* Note that the '1' edit code does not include a sign so we
* don't have to calculate the absolute value.
C
RETURN
lparen
+
C
%editc(val : '1') +
C
rparen
P editparens
E
Figure 139. %EDITC Example 2
Chapter 20. Built-in Functions
371
Built-in Functions Alphabetically
%EDITFLT (Convert to Float External Representation)
%EDITFLT(numeric expression)
%EDITFLT converts the value of the numeric expression to the character external
display representation of float. The result is either 14 or 23 characters. If the argument is a 4-byte float field, the result is 14 characters. Otherwise, it is 23 characters.
If specified as a parameter to a definition specification keyword, the parameter must
be a numeric literal, float literal, or numeric valued constant name or built-in function. When specified in an expression, constant folding is applied if the numeric
expression has a constant value.
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D f8
s
8f
inz (50000)
D string
s
40a
CL0N01Factor1+++++++Opcode&ExtExtended-factor2+++++++++++++++++++++++++++
C
eval
string = 'Float value is '
C
+ %editflt (f8 - 4e4) + '.'
* Value of "string" is 'Float value is +1.000000000000000E+004. '
Figure 140. %EDITFLT Example
372
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%EDITW (Edit Value Using an Editword)
%EDITW(numeric : editword)
This function returns a character result representing the numeric value edited
according to the edit word. The rules for the numeric value and edit word are identical to those for editing numeric values in output specifications.
Float expressions are not allowed in the first parameter. Use %DEC to convert a
float to an editable format.
The edit word must be a character constant.
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D amount
S
30A
D salary
S
9P 2
D editwd
C
'$ ,
, **Dollars& &Cents'
* If the value of salary is 2451.53, then the edited version of
* (salary * 12) is '$***29,418*Dollars 36 Cents'. The value of
* amount is 'The annual salary is $***29,418*Dollars 36 Cents'.
CL0N01Factor1+++++++Opcode&ExtExtended-factor2+++++++++++++++++++++++++++
C
EVAL
amount = 'The annual salary is '
C
+ %editw(salary * 12 : editwd)
Figure 141. %EDITW Example
Chapter 20. Built-in Functions
373
Built-in Functions Alphabetically
%ELEM (Get Number of Elements)
%ELEM(table_name)
%ELEM(array_name)
%ELEM(multiple_occurrence_data_structure_name)
%ELEM returns the number of elements in the specified array, table, or multipleoccurrence data structure. The value returned is in unsigned integer format (type
U). It may be specified anywhere a numeric constant is allowed in the definition
specification or in an expression in the extended factor 2 field.
The parameter must be the name of an array, table, or multiple occurrence data
structure.
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++++++++
D arr1d
S
20
DIM(10)
D table
S
10
DIM(20) ctdata
D mds
DS
20
occurs(30)
D num
S
5P
* like_array will be defined with a dimension of 10.
* array_dims will be defined with a value of 10.
D like_array
S
like(arr1d) dim(%elem(arr1d))
D array_dims
C
const (%elem (arr1d))
C*L0N01Factor1+++++++Opcode(E)+Extended-factor2++++++++++++++++++++++++++
*
* In the following examples num will be equal to 10, 20, and 30.
*
C
EVAL
num = %elem (arr1d)
C
EVAL
num = %elem (table)
C
EVAL
num = %elem (mds)
Figure 142. %ELEM Example
374
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%EOF (Return End or Beginning of File Condition)
%EOF{(file_name)}
%EOF returns '1' if the most recent read operation or write to a subfile ended in an
end of file or beginning of file condition; otherwise, it returns '0'.
The operations that set %EOF are:
¹ “READ (Read a Record)” on page 615
¹ “READC (Read Next Changed Record)” on page 618
¹ “READE (Read Equal Key)” on page 620
¹ “READP (Read Prior Record)” on page 623
¹ “READPE (Read Prior Equal)” on page 625
¹ “WRITE (Create New Records)” on page 685 (subfile only).
When a full-procedural file is specified, this function returns '1' if the previous operation in the list above, for the specified file, resulted in an end of file or beginning of
file condition. For primary and secondary files, %EOF is available only if the file
name is specified. It is set to '1' if the most recent input operation during *GETIN
processing resulted in an end of file or beginning of file condition. Otherwise, it
returns '0'.
This function is allowed for input, update, and record-address files; and for display
files allowing WRITE to subfile records.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++
* File INFILE has record format INREC
FINFILE
IF
E
DISK
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
* Read a record
C
READ
INREC
* If end-of-file was reached ...
C
IF
%EOF
C ...
C
ENDIF
Figure 143. %EOF without a Filename Parameter
Chapter 20. Built-in Functions
375
Built-in Functions Alphabetically
*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++
* This program is comparing two files
*
FFILE1
IF
E
DISK
FFILE2
IF
E
DISK
F
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
* Loop until either FILE1 or FILE2 has reached end-of-file
C
DOU
%EOF(FILE1) OR %EOF(FILE2)
* Read a record from each file and compare the records
*
C
READ
REC1
C
READ
REC2
C
SELECT
C
WHEN
%EOF(FILE1) AND %EOF(FILE2)
* Both files have reached end-of-file
C
EXSR
EndCompare
C
WHEN
%EOF(FILE1)
* FILE1 is shorter than FILE2
C
EXSR
F1Short
C
WHEN
%EOF(FILE2)
* FILE2 is shorter than FILE1
C
EXSR
F2Short
C
OTHER
* Both files still have records to be compared
C
EXSR
CompareRecs
C
ENDSL
C
ENDDO
...
Figure 144. %EOF with a Filename Parameter
376
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%EQUAL (Return Exact Match Condition)
%EQUAL{(file_name)}
%EQUAL returns '1' if the most recent relevant operation found an exact match;
otherwise, it returns '0'.
The operations that set %EQUAL are:
¹ “SETLL (Set Lower Limit)” on page 650
¹ “LOOKUP (Look Up a Table or Array Element)” on page 559
If %EQUAL is used without the optional file_name parameter, then it returns the
value set for the most recent relevant operation.
For the SETLL operation, this function returns '1' if a record is present whose key
or relative record number is equal to the search argument.
For the LOOKUP operation with the EQ indicator specified, this function returns '1'
if an element is found that exactly matches the search argument.
If a file name is specified, this function applies to the most recent SETLL operation
for the specified file. This function is allowed only for files that allow the SETLL
operation code.
For more examples, see Figure 241 on page 561 and Figure 285 on page 653.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++
* File CUSTS has record format CUSTREC
FCUSTS
IF
E
K DISK
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
* Check if the file contains a record with a key matching Cust
C
Cust
SETLL
CUSTREC
C
IF
%EQUAL
C ... an exact match was found in the file
C
ENDIF
Figure 145. %EQUAL with SETLL Example
Chapter 20. Built-in Functions
377
Built-in Functions Alphabetically
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D TabNames
S
10A
DIM(5) CTDATA ASCEND
D SearchName
S
10A
* Position the table at or near SearchName
* Here are the results of this program for different values
* of SearchName:
*
SearchName
|
DSPLY
*
-------------+------------------------------*
'Catherine ' |
'Next greater
Martha'
*
'Andrea
' |
'Exact
Andrea'
*
'Thomas
' |
'Not found
Thomas'
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
C
SearchName
LOOKUP
TabNames
10 10
C
SELECT
C
WHEN
%EQUAL
* An exact match was found
C
'Exact
'DSPLY
TabNames
C
WHEN
%FOUND
* A name was found greater than SearchName
C
'Next greater'DSPLY
TabNames
C
OTHER
* Not found. SearchName is greater than all the names in the table
C
'Not found
'DSPLY
SearchName
C
ENDSL
C
RETURN
**CTDATA TabNames
Alexander
Andrea
Bohdan
Martha
Samuel
Figure 146. %EQUAL and %FOUND with LOOKUP Example
378
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%ERROR (Return Error Condition)
%ERROR returns '1' if the most recent operation with extender 'E' specified
resulted in an error condition. This is the same as the error indicator being set on
for the operation. Before an operation with extender 'E' specified begins, %ERROR
is set to return '0' and remains unchanged following the operation if no error occurs.
All operations that allow an error indicator can also set the %ERROR built-in function. The CALLP operation can also set %ERROR.
For examples of the %ERROR built-in function, see Figure 163 on page 399 and
Figure 164 on page 400.
Chapter 20. Built-in Functions
379
Built-in Functions Alphabetically
%FLOAT (Convert to Floating Format)
%FLOAT(numeric expression)
%FLOAT converts the value of the numeric expression to float format. This built-in
function may only be used in expressions.
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D p1
s
15p 0 inz (1)
D p2
s
25p13 inz (3)
D result1
s
15p 5
D result2
s
15p 5
D result3
s
15p 5
CL0N01Factor1+++++++Opcode&ExtExtended-factor2+++++++++++++++++++++++++++
C
eval
result1 = p1 / p2
C
eval
result2 = %float (p1) / p2
C
eval
result3 = %float (p1 / p2)
* The value of "result1" is now 0.33000.
* The value of "result2" is now 0.33333.
* The value of "result3" is now 0.33333.
Figure 147. %FLOAT Example
380
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%FOUND (Return Found Condition)
%FOUND{(file_name)}
%FOUND returns '1' if the most recent relevant file operation found a record, a
string operation found a match, or a search operation found an element. Otherwise,
this function returns '0'.
The operations that set %FOUND are:
¹ File operations:
– “CHAIN (Random Retrieval from a File)” on page 490
– “DELETE (Delete Record)” on page 512
– “SETGT (Set Greater Than)” on page 646
– “SETLL (Set Lower Limit)” on page 650
¹ String operations:
– “CHECK (Check Characters)” on page 493
– “CHECKR (Check Reverse)” on page 496
– “SCAN (Scan String)” on page 641
Note: Built-in function %SCAN does not change the value of %FOUND.
¹ Search operations:
– “LOOKUP (Look Up a Table or Array Element)” on page 559
If %FOUND is used without the optional file_name parameter, then it returns the
value set for the most recent relevant operation. When a file_name is specified,
then it applies to the most recent relevant operation on that file.
For file operations, %FOUND is opposite in function to the "no record found NR"
indicator.
For string operations, %FOUND is the same in function as the "found FD" indicator.
For the LOOKUP operation, %FOUND returns '1' if the operation found an element
satisfying the search conditions. For an example of %FOUND with LOOKUP, see
Figure 146.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++
* File CUSTS has record format CUSTREC
FCUSTS
IF
E
K DISK
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
* Check if the customer is in the file
C
Cust
CHAIN
CUSTREC
C
IF
%FOUND
C ...
C
ENDIF
Figure 148. %FOUND used to Test a File Operation without a Parameter
Chapter 20. Built-in Functions
381
Built-in Functions Alphabetically
*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++
* File MASTER has all the customers
* File GOLD has only the "privileged" customers
FMASTER
IF
E
K DISK
FGOLD
IF
E
K DISK
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
* Check if the customer exists, but is not a privileged customer
C
Cust
CHAIN
MASTREC
C
Cust
CHAIN
GOLDREC
* Note that the file name is used for %FOUND, not the record name
C
IF
%FOUND(MASTER) AND NOT %FOUND(GOLD)
C ...
C
ENDIF
Figure 149. %FOUND used to Test a File Operation with a Parameter
*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D Numbers
C
'0123456789'
D Position
S
5I 0
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
* If the actual position of the name is not required, just use
* %FOUND to test the results of the SCAN operation.
* If Name has the value 'Barbara' and Line has the value
* 'in the city of Toronto.
', then %FOUND will return '0'.
* If Line has the value 'the city of Toronto where Barbara lives, '
* then %FOUND will return '1'.
C
Name
SCAN
Line
C
IF
%FOUND
C
EXSR
PutLine
C
ENDIF
* If Value contains the value '12345.67', Position would be set
* to 6 and %FOUND would return the value '1'.
* If Value contains the value '10203040', Position would be set
* to 0 and %FOUND would return the value '0'.
C
Numbers
CHECK
Value
Position
C
IF
%FOUND
C
EXSR
HandleNonNum
C
ENDIF
Figure 150. %FOUND used to Test a String Operation
382
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
|
|
%GRAPH (Convert to Graphic Value)
%GRAPH(char-expr | graph-expr | UCS-2-expr { : ccsid })
|
|
|
%GRAPH converts the value of the expression from character, graphic, or UCS-2
and returns a graphic value. The result is varying length if the parameter is varying
length.
|
|
|
|
The second parameter, ccsid, is optional and indicates the CCSID of the resulting
expression. The CCSID defaults to the graphic CCSID related to the CCSID of the
job. If CCSID(*GRAPH : *IGNORE) is specified on the control specification or
assumed for the module, the %GRAPH built-in is not allowed.
|
|
If the parameter is a constant, the conversion will be done at compile time. In this
case, the CCSID is the graphic CCSID related to the CCSID of the source file.
|
|
If the conversion results in substitution characters, a warning message is issued at
compile time. At run time, status 00050 is set and no error message is issued.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
H CCSID(*GRAPH : 300)
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++
D char
S
5A
INZ('abcde')
* The %GRAPH built-in function is used to initialize a graphic field
D graph
S
10G
INZ(%GRAPH('oAABBCCDDEEi'))
D ufield
S
2C
INZ(%UCS2('oFFGGi'))
D graph2
S
2G
CCSID(4396) INZ(*HIVAL)
D isEqual
S
1N
D proc
PR
D
gparm
2G
CCSID(4396) VALUE
CL0N01Factor1+++++++Opcode&ExtExtended-factor2+++++++++++++++++++++++++++
C
EVAL
graph = %GRAPH(char) + %GRAPH(ufield)
* graph now has 7 graphic characters AABBCCDDEEFFGG.
|
|
|
C
|
|
|
|
C
|
|
|
C
|
EVAL
isEqual = graph = %GRAPH(graph2 : 300)
* The result of the %GRAPH built-in function is the value of
* graph2, converted from CCSID 4396 to CCSID 300.
EVAL
graph2 = graph
* The value of graph is converted from CCSID 300 to CCSID 4396
* and stored in graph2.
* This conversion is performed implicitly by the compiler.
CALLP
proc(graph)
* The value of graph is converted from CCSID 300 to CCSID 4396
* implicitly, as part of passing the parameter by value.
Figure 151. %GRAPH Examples
Chapter 20. Built-in Functions
383
Built-in Functions Alphabetically
%INT (Convert to Integer Format)
%INT(numeric expression)
%INT converts the value of the numeric expression to integer. Any decimal digits
are truncated. This built-in function may only be used in expressions. %INT can be
used to truncate the decimal positions from a float or decimal value allowing it to be
used as an array index.
%INTH (Convert to Integer Format with Half Adjust)
%INTH(numeric expression)
%INTH is the same as %INT except that if the numeric expression is a decimal or
float value, half adjust is applied to the value of the numeric expression when converting to integer type. No message is issued if half adjust cannot be performed.
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D p7
s
7p 3 inz (1234.567)
D s9
s
9s 5 inz (73.73442)
D f8
s
8f
inz (123.789)
D result1
s
15p 5
D result2
s
15p 5
D result3
s
15p 5
D array
s
1a
dim (200)
D a
s
1a
CL0N01Factor1+++++++Opcode&ExtExtended-factor2+++++++++++++++++++++++++++
C
eval
result1 = %int (p7) + 0.011
C
eval
result2 = %int (s9)
C
eval
result3 = %inth (f8)
* The value of "result1" is now 1234.01100.
* The value of "result2" is now
73.00000
* The value of "result3" is now 124.00000.
C
eval
a = array (%inth (f8))
* %INT and %INTH can be used as array indexes
Figure 152. %INT and %INTH Example
384
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%LEN (Get or Set Length)
%LEN(expression)
%LEN can be used to get the length of a variable expression or to set the current
length of a variable-length field.
The parameter must not be a figurative constant.
%LEN Used for its Value
When used on the right-hand side of an expression, this function returns the
number of digits or characters of the variable expression.
For numeric expressions, the value returned represents the precision of the
expression and not necessarily the actual number of significant digits. For a float
variable or expression, the value returned is either 4 or 8. When the parameter is a
numeric literal, the length returned is the number of digits of the literal.
|
|
For character, graphic, or UCS-2 expressions the value returned is the number of
characters in the value of the expression. For variable-length values, such as the
value returned from a built-in function or a variable-length field, the value returned
by %LEN is the current length of the character, graphic, or UCS-2 value.
Note that if the parameter is a built-in function or expression that has a value computable at compile-time, the length returned is the actual number of digits of the
constant value rather than the maximum possible value that could be returned by
the expression.
For all other data types, the value returned is the number of bytes of the value.
Chapter 20. Built-in Functions
385
Built-in Functions Alphabetically
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D num1
S
7P 2
D num2
S
5S 1
D num3
S
5I 0 inz(2)
D chr1
S
10A
inz('Toronto
')
D chr2
S
10A
inz('Munich
')
D ptr
S
*
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
* Numeric expressions:
C
eval
num1 = %len(num1)
<=== 7
C
eval
num1 = %decpos(num2)
<=== 1
C
eval
num1 = %len(num1*num2)
<=== 12
C
eval
num1 = %decpos(num1*num2)
<=== 3
* Character expressions:
C
eval
num1 = %len(chr1)
<=== 10
C
eval
num1 = %len(chr1+chr2)
<=== 20
C
eval
num1 = %len(%trim(chr1))
<=== 7
C
eval
num1 = %len(%subst(chr1:1:num3)
C
+ ' ' + %trim(chr2))
<=== 9
* %len and %decpos can be useful with other built-in functions:
* Although this division is performed in float, the result is
* converted to the same precision as the result of the eval:
C
eval
num1 = 27 + %dec (%float(num1)/num3
C
: %len(num1)
C
: %decpos(num1))
* Allocate sufficient space to hold the result of the catenation
* (plus an extra byte for a trailing null character):
C
eval
num3 = %len(chr1+chr2)+1
C
alloc
num3
ptr
C
eval
%str(ptr : num3) = chr1 + chr2
Figure 153. %DECPOS and %LEN Example
%LEN Used to Set the Length of Variable-Length Fields
When used on the left-hand side of an expression, this function sets the current
length of a variable-length field. If the set length is greater than the current length,
the characters in the field between the old length and the new length are set to
blanks.
Note: %LEN can only be used on the left-hand-side of an expression when the
parameter is variable length.
386
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
*
D city
S
40A
VARYING INZ('North York')
D n1
S
5i 0
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
* %LEN used to get the current length of a variable-length field:
C
EVAL
n1 = %LEN(city)
* Current length, n1 = 10
*
* %LEN used to set the current length of a variable-length field:
C
EVAL
%LEN(city) = 5
* city = 'North' (length is 5)
*
C
EVAL
%LEN(city) = 15
* city = 'North
' (length is 15)
Figure 154. %LEN with Variable-Length Field Example
Chapter 20. Built-in Functions
387
Built-in Functions Alphabetically
%NULLIND (Query or Set Null Indicator)
%NULLIND(fieldname)
The %NULLIND built-in function can be used to query or set the null indicator for
null-capable fields. This built-in function can only be used if the
ALWNULL(*USRCTL) keyword is specified on a control specification or as a
command parameter. The fieldname can be a null-capable array element, data
structure, stand-alone field, subfield, or multiple occurrence data structure.
%NULLIND can only be used in expressions in extended factor 2.
When used on the right-hand side of an expression, this function returns the setting
of the null indicator for the null-capable field. The setting can be *ON or *OFF.
When used on the left-hand side of an expression, this function can be used to set
the null indicator for null-capable fields to *ON or *OFF. The content of a nullcapable field remains unchanged.
See “Database Null Value Support” on page 198 for more information on handling
records with null-capable fields and keys.
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
*
* Test the null indicator for a null-capable field.
*
C
IF
%NULLIND(fieldname1)
C
:
C
ENDIF
*
* Set the null indicator for a null-capable field.
*
C
EVAL
%NULLIND(fieldname1) = *ON
C
EVAL
%NULLIND(fieldname2) = *OFF
Figure 155. %NULLIND Example
388
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%OPEN (Return File Open Condition)
%OPEN(file_name)
%OPEN returns '1' if the specified file is open. A file is considered "open" if it has
been opened by the RPG program during initialization or by an OPEN operation,
and has not subsequently been closed. If the file is conditioned by an external
indicator and the external indicator was off at program initialization, the file is considered closed, and %OPEN returns '0'.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....
FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords++++++++++++++++++++++++++++
* The printer file is opened in the calculation specifications
FQSYSPRT
O
F 132
PRINTER USROPN
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
* Open the file if it is not already open
C
IF
NOT %OPEN(QSYSPRT)
C
OPEN
QSYSPRT
C
ENDIF
...
Figure 156. %OPEN Example
Chapter 20. Built-in Functions
389
Built-in Functions Alphabetically
%PADDR (Get Procedure Address)
%PADDR(string)
%PADDR returns a value of type procedure pointer. The value is the address of the
entry point specified as the argument.
%PADDR may be compared with and assigned to only items of type procedure
pointer.
The parameter to %PADDR must be a character or hexadecimal literal or a constant name that represents a character or hexadecimal literal. The entry point name
specified by the character string must be found at program bind time and must be
in the correct case.
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D
D PROC
S
*
PROCPTR
D
INZ (%PADDR ('FIRSTPROG'))
D PROC1
S
*
PROCPTR
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
*
* The following statement calls procedure 'FIRSTPROG'.
*
C
CALLB
PROC
*----------------------------------------------------------------* The following statements call procedure 'NextProg'.
* This a C procedure and is in mixed case. Note that
* the procedure name is case sensitive.
*
C
EVAL
PROC1 = %PADDR ('NextProg')
C
CALLB
PROC1
Figure 157. %PADDR Example
390
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%PARMS (Return Number of Parameters)
%PARMS returns the number of parameters that were passed to the procedure in
which %PARMS is used. For the main procedure, %PARMS is the same as
*PARMS.
The value returned by %PARMS is not available if the program or procedure that
calls %PARMS does not pass a minimal operational descriptor. The ILE
RPGcompiler always passes one, but other languages do not. So if the caller is
written in another ILE language, it will need to pass an operational descriptor on the
call. If the operational descriptor is not passed, the value returned by %PARMS
cannot be trusted.
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
* Prototype for procedure MaxInt which calculates the maximum
* value of its parameters (at least 2 parameters must be passed)
D MaxInt
PR
10I 0
D p1
10I 0 VALUE
D p2
10I 0 VALUE
D p3
10I 0 VALUE OPTIONS(*NOPASS)
D p4
10I 0 VALUE OPTIONS(*NOPASS)
D p5
10I 0 VALUE OPTIONS(*NOPASS)
D Fld1
S
10A
DIM(40)
D Fld2
S
20A
D Fld3
S
100A
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
C
*ENTRY
PLIST
C
PARM
MaxSize
10 0
* Make sure the main procedure was passed a parameter
C
IF
%PARMS < 1
C
'No parms'
DSPLY
C
RETURN
C
ENDIF
* Determine the maximum size of Fld1, Fld2 and Fld3
C
EVAL
MaxSize = MaxInt(%size(Fld1:*ALL) :
C
%size(Fld2) :
C
%size(Fld3))
C
'MaxSize is' DSPLY
MaxSize
C
RETURN
Figure 158 (Part 1 of 2). %PARMS Example
Chapter 20. Built-in Functions
391
Built-in Functions Alphabetically
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
*---------------------------------------------------------------* MaxInt - return the maximum value of the passed parameters
*---------------------------------------------------------------P MaxInt
B
D MaxInt
PI
10I 0
D p1
10I 0 VALUE
D p2
10I 0 VALUE
D p3
10I 0 VALUE OPTIONS(*NOPASS)
D p4
10I 0 VALUE OPTIONS(*NOPASS)
D p5
10I 0 VALUE OPTIONS(*NOPASS)
D Max
S
10I 0 INZ(*LOVAL)
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
* Branch to the point in the calculations where we will never
* access unpassed parameters.
C
SELECT
C
WHEN
%PARMS = 2
C
GOTO
PARMS2
C
WHEN
%PARMS = 3
C
GOTO
PARMS3
C
WHEN
%PARMS = 4
C
GOTO
PARMS4
C
WHEN
%PARMS = 5
C
GOTO
PARMS5
C
ENDSL
* Determine the maximum value. Max was initialized to *LOVAL.
C
PARMS5
TAG
C
IF
p5 > Max
C
EVAL
Max = p5
C
ENDIF
*
C
PARMS4
TAG
C
IF
p4 > Max
C
EVAL
Max = p4
C
ENDIF
*
C
PARMS3
TAG
C
IF
p3 > Max
C
EVAL
Max = p3
C
ENDIF
*
C
PARMS2
TAG
C
IF
p2 > Max
C
EVAL
Max = p2
C
ENDIF
C
IF
p1 > Max
C
EVAL
Max = p1
C
ENDIF
C
RETURN
Max
P MaxInt
E
Figure 158 (Part 2 of 2). %PARMS Example
392
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
|
|
%REM (Return Integer Remainder)
%REM(n:m)
|
|
|
|
|
|
|
%REM returns the remainder that results from dividing operands n by m. The two
operands must be numeric values with zero decimal positions. If either operand is a
packed, zoned, or binary numeric value, the result is packed numeric. If either
operand is an integer numeric value, the result is integer. Otherwise, the result is
unsigned numeric. Float numeric operands are not allowed. The result has the
same sign as the dividend. (See also “%DIV (Return Integer Portion of Quotient)”
on page 368.)
|
%REM and %DIV have the following relationship:
|
%REM(A:B) = A - (%DIV(A:B) * B)
|
|
|
If the operands are constants that can fit in 8-byte integer or unsigned fields, constant folding is applied to the built-in function. In this case, the %REM built-in function can be coded in the definition specifications.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
*
D A
S
10I 0 INZ(123)
D B
S
10I 0 INZ(27)
D DIV
S
10I 0
D REM
S
10I 0
D E
S
10I 0
*
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
*
C
EVAL
DIV = %DIV(A:B)
C
EVAL
REM = %REM(A:B)
C
EVAL
E = DIV*B + REM
* Now, DIV = 4, REM = 15, E = 123
Figure 159. %DIV and %REM Example
Chapter 20. Built-in Functions
393
Built-in Functions Alphabetically
%REPLACE (Replace Character String)
%REPLACE(replacement string: source string{:start position {:source
length to replace}})
%REPLACE returns the character string produced by inserting a replacement string
into the source string, starting at the start position and replacing the specified
number of characters.
|
The first and second parameter must be of type character, graphic, or UCS-2 and
can be in either fixed- or variable-length format. The second parameter must be the
same type as the first.
The third parameter represents the starting position, measured in characters, for
the replacement string. If it is not specified, the starting position is at the beginning
of the source string. The value may range from one to the current length of the
source string plus one.
The fourth parameter represents the number of characters in the source string to
be replaced. If zero is specified, then the replacement string is inserted before the
specified starting position. If the parameter is not specified, the number of characters replaced is the same as the length of the replacement string. The value must
be greater than or equal to zero, and less than or equal to the current length of the
source string.
The starting position and length may be any numeric value or numeric expression
with no decimal positions.
The returned value is varying length if the source string or replacement string are
varying length, or if the start position or source length to replace are variables. Otherwise, the result is fixed length.
394
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D var1
S
30A
INZ('Windsor') VARYING
D var2
S
30A
INZ('Ontario') VARYING
D var3
S
30A
INZ('Canada') VARYING
D fixed1
S
15A
INZ('California')
D date
S
D
INZ(D'1997-02-03')
D result
S
100A
VARYING
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
C
C
EVAL
result = var1 + ', ' + 'ON'
* result = 'Windsor, ON'
*
* %REPLACE with 2 parameters to replace text at begining of string:
C
EVAL
result = %REPLACE('Toronto': result)
* result = 'Toronto, ON'
*
* %REPLACE with 3 parameters to replace text at specified position:
C
EVAL
result = %REPLACE(var3: result:
C
%SCAN(',': result)+2)
* result = 'Toronto, Canada'
*
* %REPLACE with 4 parameters to insert text:
C
EVAL
result = %REPLACE(', '+var2: result:
C
%SCAN(',': result): 0)
* result = 'Toronto, Ontario, Canada'
*
* %REPLACE with 4 parameters to replace strings with different lengths:
C
EVAL
result = %REPLACE('Scarborough': result:
C
1: %SCAN(',': result)-1)
* result = 'Scarborough, Ontario, Canada'
*
* %REPLACE with 4 parameters to delete text:
C
EVAL
result = %REPLACE('': result: 1:
C
%SCAN(',': result)+1)
* result = 'Ontario, Canada'
*
* %REPLACE with 4 parameters to add text to the end of the string:
C
EVAL
result = %REPLACE(', ' + %CHAR(date):
C
result:
C
%LEN(result)+1: 0)
* result = 'Ontario, Canada, 1997-02-03'
*
* %REPLACE with 3 parameters to replace fixed-length text at
* specified position: (fixed1 has fixed-length of 15 chars)
C
EVAL
result = %REPLACE(fixed1: result:
C
%SCAN(',': result)+2)
* result = 'Ontario, California
-03'
*
* %REPLACE with 4 parameters to prefix text at beginning:
C
EVAL
result = %REPLACE('Somewhere else: ':
C
result: 1: 0)
* result = 'Somewhere else: Ontario, California
-03'
Figure 160. %REPLACE Example
Chapter 20. Built-in Functions
395
Built-in Functions Alphabetically
%SCAN (Scan for Characters)
%SCAN(search argument : source string {: start})
%SCAN returns the first position of the search argument in the source string, or 0 if
it was not found. If the start position is specified, the search begins at the starting
position. The result is always the position in the source string even if the starting
position is specified. The starting position defaults to 1.
|
The first parameter must be of type character, graphic, or UCS-2 . The second
parameter must be the same type as the first parameter. The third parameter, if
specified, must be numeric with zero decimal positions.
When any parameter is variable in length, the values of the other parameters are
checked against the current length, not the maximum length.
The type of the return value is unsigned integer. This built-in function can be used
anywhere that an unsigned integer expression is valid.
Note: Unlike the SCAN operation code, %SCAN cannot return an array containing
all occurrences of the search string and its results cannot be tested using
the %FOUND built-in function.
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D source
S
15A inz('Dr. Doolittle')
D pos
S
5U 0
CL0N01Factor1+++++++Opcode&ExtExtended-factor2+++++++++++++++++++++++++++
C
EVAL
pos = %scan('oo' : source)
* After the EVAL, pos = 6 because 'oo' begins at position 6 in
* 'Dr. Doolittle'.
C
EVAL
pos = %scan('D' : source : 2)
* After the EVAL, pos = 5 because the first 'D' found starting from
* position 2 is in position 5.
C
EVAL
pos = %scan('abc' : source)
* After the EVAL, pos = 0 because 'abc' is not found in
* 'Dr. Doolittle'.
C
EVAL
pos = %scan('Dr.' : source : 2)
* After the EVAL, pos = 0 because 'Dr.' is not found in
* 'Dr. Doolittle', if the search starts at position 2.
Figure 161. %SCAN Example
396
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%SIZE (Get Size in Bytes)
%SIZE(variable)
%SIZE(literal)
%SIZE(array{:*ALL})
%SIZE(table{:*ALL})
%SIZE(multiple occurrence data structure{:*ALL})
%SIZE returns the number of bytes occupied by the constant or field. The argument may be a literal, a named constant, a data structure, a data structure subfield,
a field, an array or a table name. It cannot, however, contain an expression. The
value returned is in unsigned integer format (type U).
|
|
|
For a graphic literal, the size is the number of bytes occupied by the graphic characters, not including leading and trailing shift characters. For a hexadecimal or
UCS-2 literal, the size returned is half the number of hexadecimal digits in the
literal.
For variable-length fields, %SIZE returns the total number of bytes occupied by the
field (two bytes longer than the declared maximum length).
The length returned for a null-capable field (%SIZE) is always its full length, regardless of the setting of its null indicator.
If the argument is an array name, table name, or multiple occurrence data structure
name, the value returned is the size of one element or occurrence. If *ALL is specified as the second parameter for %SIZE, the value returned is the storage taken
up by all elements or occurrences. For a multiple-occurrence data structure containing pointer subfields, the size may be greater than the size of one occurrence
times the number of occurrences. The system requires that pointers be placed in
storage at addresses evenly divisible by 16. As a result, the length of each occurrence may have to be increased enough to make the length an exact multiple of 16
so that the pointer subfields will be positioned correctly in storage for every occurrence.
%SIZE may be specified anywhere that a numeric constant is allowed on the definition specification and in an expression in the extended factor 2 field of the calculation specification.
Chapter 20. Built-in Functions
397
Built-in Functions Alphabetically
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D
D arr1
S
10
DIM(4)
D table1
S
5
DIM(20)
D field1
S
10
D field2
S
9B 0
D field3
S
5P 2
D num
S
5P 0
D mds
DS
20
occurs(10)
D mds_size
C
const (%size (mds: *all))
D mds_ptr
DS
20
OCCURS(10)
D
pointer
*
D vCity
S
40A
VARYING INZ('North York')
D fCity
S
40A
INZ('North York')
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
C
Result
C
eval
num = %SIZE(field1)
10
C
eval
num = %SIZE('HH')
2
C
eval
num = %SIZE(123.4)
4
C
eval
num = %SIZE(-03.00)
4
C
eval
num = %SIZE(arr1)
10
C
eval
num = %SIZE(arr1:*ALL)
40
C
eval
num = %SIZE(table1)
5
C
eval
num = %SIZE(table1:*ALL)
100
C
eval
num = %SIZE(mds)
20
C
eval
num = %SIZE(mds:*ALL)
200
C
EVAL
num = %SIZE(mds_ptr)
20
C
EVAL
num = %SIZE(mds_ptr:*ALL)
320
C
eval
num = %SIZE(field2)
4
C
eval
num = %SIZE(field3)
3
C
eval
n1 = %SIZE(vCity)
42
C
EVAL
n2 = %SIZE(fCity)
40
Figure 162. %SIZE Example
398
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%STATUS (Return File or Program Status)
%STATUS{(file_name)}
%STATUS returns the most recent value set for the program or file status.
%STATUS is set whenever the program status or any file status changes, usually
when an error occurs.
If %STATUS is used without the optional file_name parameter, then it returns the
program or file status most recently changed. If a file is specified, the value contained in the INFDS *STATUS field for the specified file is returned. The INFDS
does not have to be specified for the file.
%STATUS starts with a return value of 00000 and is reset to 00000 before any
operation with an 'E' extender specified begins.
%STATUS is best checked immediately after an operation with the 'E' extender or
an error indicator specified, or at the beginning of an INFSR or the *PSSR subroutine.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
* The 'E' extender indicates that if an error occurs, the error
* is to be handled as though an error indicator were coded.
* The success of the operation can then be checked using the
* %ERROR built-in function. The status associated with the error
* can be checked using the %STATUS built-in function.
C
EXFMT(E) INFILE
C
IF
%ERROR
C
EXSR
CheckError
C
ENDIF
C ...
*------------------------------------------------------------------* CheckError: Subroutine to process a file I/O error
*------------------------------------------------------------------C
CheckError
BEGSR
C
SELECT
C
WHEN
%STATUS < 01000
* No error occurred
C
WHEN
%STATUS = 01211
* Attempted to read a file that was not open
C
EXSR
InternalError
C
WHEN
%STATUS = 01331
* The wait time was exceeded for a READ operation
C
EXSR
TimeOut
C
WHEN
%STATUS = 01261
* Operation to unacquired device
C
EXSR
DeviceError
C
WHEN
%STATUS = 01251
* Permanent I/O error
C
EXSR
PermError
C
OTHER
* Some other error occurred
C
EXSR
FileError
C
ENDSL
C
ENDSR
Figure 163. %STATUS and %ERROR with 'E' Extender
Chapter 20. Built-in Functions
399
Built-in Functions Alphabetically
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++++++++++++++++++++++++++
D Zero
S
5P 0 INZ(0)
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
* %STATUS starts with a value of 0
*
* The following SCAN operation will cause a branch to the *PSSR
* because the start position has a value of 0.
C
'A'
SCAN
'ABC':Zero
Pos
C
BAD_SCAN
TAG
* The following EXFMT operation has an 'E' extender, so %STATUS will
* be set to 0 before the operation begins. Therefore, it is
* valid to check %STATUS after the operation.
* Since the 'E' extender was coded, %ERROR can also be used to
* check if an error occurred.
C
EXFMT(E) REC1
C
IF
%ERROR
C
SELECT
C
WHEN
%STATUS = 01255
C ...
C
WHEN
%STATUS = 01299
C ...
* The following scan operation has an error indicator. %STATUS will
* not be set to 0 before the operation begins, but %STATUS can be
* reasonably checked if the error indicator is on.
C
'A'
SCAN
'ABC':Zero
Pos
10
C
IF
*IN10 AND %STATUS = 00100
C ...
*
*
*
*
*
*
*
The following scan operation does not produce an error.
Since there is no 'E' extender %STATUS will not be set to 0,
so it would return a value of 00100 from the previous error.
Therefore, it is unwise to use %STATUS after an operation that
does not have an error indicator or the 'E' extender coded since
you cannot be sure that the value pertains to the previous
operation.
C
'A'
SCAN
'ABC'
Pos
C ...
C
*PSSR
BEGSR
* %STATUS can be used in the *PSSR since an error must have occurred.
C
IF
%STATUS = 00100
C
GOTO
BAD_SCAN
C ...
Figure 164. %STATUS and %ERROR with 'E' Extender, Error Indicator and *PSSR
400
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%STR (Get or Store Null-Terminated String)
%STR(basing pointer{: max-length})(right-hand-side)
%STR(basing pointer : max-length)(left-hand-side)
|
|
%STR is used to create or use null-terminated character strings, which are very
commonly used in C and C++ applications.
The first parameter must be a basing-pointer variable. The second parameter, if
specified, must be a numeric value with zero decimal positions. If not specified, it
defaults to 65535 .
The first parameter must point to storage that is at least as long as the length given
by the second parameter.
Error conditions:
|
1. If the length parameter is not between 1 and 65535 , an error will occur.
2. If the pointer is not set, an error will occur.
3. If the storage addressed by the pointer is shorter than indicated by the length
parameter, either
a. An error will occur
b. Data corruption will occur.
%STR Used to Get Null-Terminated String
When used on the right-hand side of an expression, this function returns the data
pointed to by the first parameter up to but not including the first null character
(x'00') found within the length specified. This built-in function can be used anywhere
that a character expression is valid. No error will be given at run time if the null
terminator is not found within the length specified. In this case, the length of the
resulting value is the same as the length specified.
D String1
S
*
D Fld1
S
10A
C
EVAL
Fld1 = '<' + %str(String1) + '>'
* Assuming that String1 points to '123¬' where '¬' represents the
* null character, after the EVAL, Fld1 = '<123>
'.
Figure 165. %STR (right-hand-side) Example 1
The following is an example of %STR with the second parameter specified.
D String1
S
*
D Fld1
S
10A
C
EVAL
Fld1 = '<' + %str(String1 : 2) + '>'
* Assuming that String1 points to '123¬' where '¬' represents the
* null character, after the EVAL, Fld1 = '<12>
'.
* Since the maximum length read by the operation was 2, the '3' and
* the '¬' were not considered.
Figure 166. %STR (right-hand-side) Example 2
In this example, the null-terminator is found within the specified maximum length.
Chapter 20. Built-in Functions
401
Built-in Functions Alphabetically
D String1
S
*
D Fld1
S
10A
C
EVAL
Fld1 = '<' + %str(String1 : 5) + '>'
* Assuming that String1 points to '123¬' where '¬' represents the
* null character, after the EVAL, Fld1 = '<123>
'.
* Since the maximum length read by the operation was 5, the
* null-terminator in position 4 was found so all the data up to
* the null-terminator was used.
Figure 167. %STR (right-hand-side) Example 3
%STR Used to Store Null-Terminated String
When used on the left-hand side of an expression, %STR(ptr:length) assigns the
value of the right-hand side of the expression to the storage pointed at by the
pointer, adding a null-terminating byte at the end. The maximum length that can be
specified is 65535 . This means that at most 65534 bytes of the right-hand side can
be used, since 1 byte must be reserved for the null-terminator at the end.
|
The length indicates the amount of storage that the pointer points to. This length
should be greater than the maximum length the right-hand side will have. The
pointer must be set to point to storage at least as long as the length parameter. If
the length of the right-hand side of the expression is longer than the specified
length, the right-hand side value is truncated.
Note: Data corruption will occur if both of the following are true:
1. The length parameter is greater than the actual length of data
addressed by the pointer.
2. The length of the right-hand side is greater than or equal to the actual
length of data addressed by the pointer.
If you are dynamically allocating storage for use by %STR, you must keep
track of the length that you have allocated.
D String1
S
*
D Fld1
S
10A
...
C
EVAL
%str(String1:25) = 'abcdef'
* The storage pointed at by String1 now contains 'abcdef¬'
* Bytes 8-25 following the null-terminator are unchanged.
D String1
S
*
D Fld1
S
10A
...
C
EVAL
%str(String1 : 4) = 'abcdef'
* The storage pointed at by String1 now contains 'abc¬'
Figure 168. %STR (left-hand-side) Examples
402
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%SUBST (Get Substring)
%SUBST(string:start{:length})
%SUBST returns a portion of argument string. It may also be used as the result of
an assignment with the EVAL operation code.
The start parameter represents the starting position of the substring.
The length parameter represents the length of the substring. If it is not specified,
the length is the length of the string parameter less the start value plus one.
|
The string must be character, graphic, or UCS-2 data. Starting position and length
may be any numeric value or numeric expression with zero decimal positions. The
starting position must be greater than zero. The length may be greater than or
equal to zero.
When the string parameter is varying length, the values of the other parameters are
checked against the current length, not the maximum length.
When specified as a parameter for a definition specification keyword, the parameters must be literals or named constants representing literals. When specified on a
free-form calculation specification, the parameters may be any expression.
%SUBST Used for its Value
|
%SUBST returns a substring from the contents of the specified string. The string
may be any character, graphic, or UCS-2 field or expression. Unindexed arrays are
allowed for string, start, and length. The substring begins at the specified starting
position in the string and continues for the length specified. If length is not specified
then the substring continues to the end of the string. For example:
The value of
The value of
The value of
|
%subst('Hello World': 5+2) is 'World'
%subst('Hello World':5+2:10-7) is 'Wor'
%subst('abcd' + 'efgh':4:3) is 'def'
For graphic or UCS-2 characters the start position and length is consistent with the
2-byte character length (position 3 is the third 2-byte character and length 3 represents 3 2-byte characters to be operated on).
%SUBST Used as the Result of an Assignment
When used as the result of an assignment this built-in function refers to certain
positions of the argument string. Unindexed arrays are not allowed for start and
length.
The result begins at the specified starting position in the variable and continues for
the length specified. If the length is not specified then the string is referenced to its
end. If the length refers to characters beyond the end of the string, then a run-time
error is issued.
When %SUBST is used as the result of an assignment, the first parameter must
refer to a storage location. That is, the first parameter of the %SUBST operation
must be one of the following.
¹ Field
¹ Data Structure
¹ Data Structure Subfield
Chapter 20. Built-in Functions
403
Built-in Functions Alphabetically
¹ Array Name
¹ Array Element
¹ Table Element
Any valid expressions are permitted for the second and third parameters of
%SUBST when it appears as the result of an assignment with an EVAL operation.
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
*
* In this example, CITY contains 'Toronto, Ontario'
* %SUBST returns the value 'Ontario'.
*
C
' '
SCAN
CITY
C
C
IF
%SUBST(CITY:C+1) = 'Ontario'
C
EVAL
CITYCNT = CITYCNT+1
C
ENDIF
*
* Before the EVAL, A has the value 'abcdefghijklmno'.
* After the EVAL A has the value 'ab****ghijklmno'
*
C
EVAL
%SUBST(A:3:4) = '****'
Figure 169. %SUBST Example
404
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%TRIM (Trim Blanks at Edges)
%TRIM(string)
%TRIM returns the given string less any leading and trailing blanks.
|
The string can be character, graphic, or UCS-2 data.
When specified as a parameter for a definition specification keyword, the string
parameter must be a constant.
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D
D LOCATION
S
16A
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
*
* LOCATION will have the value 'Toronto, Ontario'.
*
C
EVAL
LOCATION = %TRIM(' Toronto, Ontario ')
*
* Name will have the value 'Chris Smith'.
*
C
MOVE(P)
'Chris'
FIRSTNAME
10
C
MOVE(P)
'Smith'
LASTNAME
10
C
EVAL
NAME =
C
%TRIM(FIRSTNAME) +' '+ %TRIM(LASTNAME)
Figure 170. %TRIM Example
Chapter 20. Built-in Functions
405
Built-in Functions Alphabetically
%TRIML (Trim Leading Blanks)
%TRIML(string)
%TRIML returns the given string less any leading blanks.
|
The string can be character, graphic, or UCS-2 data.
When specified as a parameter for a definition specification keyword, the string
parameter must be a constant.
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
*
* LOCATION will have the value 'Toronto, Ontario '.
*
C
EVAL
LOCATION = %TRIML(' Toronto, Ontario ')
Figure 171. %TRIML Example
406
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%TRIMR (Trim Trailing Blanks)
%TRIMR(string)
%TRIMR returns the given string less any trailing blanks.
|
The string can be character, graphic, or UCS-2 data.
When specified as a parameter for a definition specification keyword, the string
parameter must be a constant.
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D
D LOCATION
S
18A
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq..
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
*
* LOCATION will have the value ' Toronto, Ontario'.
*
C
EVAL
LOCATION = %TRIMR(' Toronto, Ontario ')
*
* Name will have the value 'Chris Smith'.
*
C
MOVEL(P) 'Chris'
FIRSTNAME
10
C
MOVEL(P) 'Smith'
LASTNAME
10
C
EVAL
NAME =
C
%TRIMR(FIRSTNAME) +' '+ %TRIMR(LASTNAME)
Figure 172. %TRIMR Example
Chapter 20. Built-in Functions
407
Built-in Functions Alphabetically
|
|
|
|
%UCS2 (Convert to UCS-2 Value)
%UCS2 converts the value of the expression from character, graphic, or UCS-2
and returns a UCS-2 value. The result is varying length if the parameter is varying
length, or if the parameter is single-byte character.
|
|
The second parameter, ccsid, is optional and indicates the CCSID of the resulting
expression. The CCSID defaults to 13488.
|
If the parameter is a constant, the conversion will be done at compile time.
|
|
If the conversion results in substitution characters, a warning message is issued at
compile time. At run time, status 00050 is set and no error message is issued.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
H CCSID(*UCS2 : 13488)
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++
D char
S
5A
INZ('abcde')
D graph
S
2G
INZ(G'oAABBi')
* The %UCS2 built-in function is used to initialize a UCS-2 field.
D ufield
S
10C
INZ(%UCS2('abcdefghij'))
D ufield2
S
1C
CCSID(61952) INZ(*LOVAL)
D isLess
1N
D proc
PR
D
uparm
2G
CCSID(13488) CONST
CL0N01Factor1+++++++Opcode&ExtExtended-factor2+++++++++++++++++++++++++
C
EVAL
ufield = %UCS2(char) + %UCS2(graph)
* ufield now has 7 UCS-2 characters representing
* 'a.b.c.d.e.AABB' where 'x.' represents the UCS-2 form of 'x'
|
|
|
|
C
|
|
|
|
C
|
|
|
C
EVAL
isLess = ufield < %UCS2(ufield2:13488)
* The result of the %UCS2 built-in function is the value of
* ufield2, converted from CCSID 61952 to CCSID 13488
* for the comparison.
EVAL
ufield = ufield2
* The value of ufield2 is converted from CCSID 61952 to
* CCSID 13488 and stored in ufield.
* This conversion is handled implicitly by the compiler.
CALLP
proc(ufield2)
* The value of ufield2 is converted to CCSID 13488
* implicitly, as part of passing the parameter by constant reference.
|
Figure 173. %UCS2 Examples
408
ILE RPG for AS/400 Reference
Built-in Functions Alphabetically
%UNS (Convert to Unsigned Format)
%UNS(numeric expression)
%UNS converts the value of the numeric expression to unsigned format. Any
decimal digits are truncated. %UNS can be used to truncate the decimal positions
from a float or decimal value allowing it to be used as an array index.
%UNSH (Convert to Unsigned Format with Half Adjust)
%UNSH(numeric expression)
%UNSH is like %UNS except that if the numeric expression is a decimal or a float
value, half adjust is applied to the value of the numeric expression when converting
to unsigned type. No message is issued if half adjust cannot be performed.
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++
D p7
s
7p 3 inz (8236.567)
D s9
s
9s 5 inz (23.73442)
D f8
s
8f
inz (173.789)
D result1
s
15p 5
D result2
s
15p 5
D result3
s
15p 5
D array
s
1a
dim (200)
D a
s
1a
CL0N01Factor1+++++++Opcode&ExtExtended-factor2+++++++++++++++++++++++++++
C
eval
result1 = %uns (p7) + 0.1234
C
eval
result2 = %uns (s9)
C
eval
result3 = %unsh (f8)
* The value of "result1" is now 8236.12340.
* The value of "result2" is now
23.00000
* The value of "result3" is now 174.00000.
C
eval
a = array (%unsh (f8))
* %UNS and %UNSH can be used as array indexes
Figure 174. %UNS and %UNSH Example
Chapter 20. Built-in Functions
409
Built-in Functions Alphabetically
|
|
%XFOOT (Sum Array Expression Elements)
%XFOOT(array-expression)
|
|
%XFOOT results in the sum of all elements of the specified numeric array
expression.
|
|
|
|
The precision of the result is the minimum that can hold the result of adding
together all array elements, up to a maximum of 30 digits. The number of decimal
places in the result is always the same as the decimal places of the array
expression.
|
|
For example, if ARR is an array of 500 elements of precision (17,4), the result of
%XFOOT(ARR) is (20,4).
|
|
For %XFOOT(X) where X has precision (m,n), the following table shows the precision of the result based on the number of elements of X:
|
|
|
|
|
|
|
Elements of X
1
2-10
11-100
101-1000
1001-10000
10001-32767
|
|
|
Normal rules for array expressions apply. For example, if ARR1 has 10 elements
and ARR2 has 20 elements, %XFOOT(ARR1+ARR2) results in the sum of the first
10 elements of ARR1+ARR2.
|
|
This built-in function is similar to the XFOOT operation, except that float arrays are
summed like all other types, beginning from index 1 on up.
410
ILE RPG for AS/400 Reference
Precision of %XFOOT(X)
(m,n)
(m+1,n)
(m+2,n)
(m+3,n)
(m+4,n)
(m+5,n)
Chapter 21. Expressions
Expressions are a way to express program logic using free-form syntax. They can
be used to write program statements in a more readable or concise manner than
fixed-form statements.
An expression is simply a group of operands and operations. For example, the following are valid expressions:
A+B*21
STRINGA + STRINGB
D = %ELEM(ARRAYNAME)
*IN01 OR (BALANCE > LIMIT)
SUM + TOTAL(ARRAY:%ELEM(ARRAY))
'The tax rate is ' + %editc(tax : 'A') + '%.'
Expressions may be coded in the following statements:
¹ “CALLP (Call a Prototyped Procedure or Program)” on page 482
¹ “DOU (Do Until)” on page 516
¹ “DOW (Do While)” on page 519
¹ “EVAL (Evaluate expression)” on page 529
|
¹ “EVALR (Evaluate expression, right adjust)” on page 531
|
¹ “FOR (For)” on page 540
¹ “IF (If)” on page 546
¹ “RETURN (Return to Caller)” on page 637
¹ “WHEN (When True Then Select)” on page 681
Figure 175 on page 412 shows several examples of how expressions can be used:
 Copyright IBM Corp. 1994, 1999
411
General Expression Rules
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
* The operations within the DOU group will iterate until the
* logical expression is true. That is, either COUNTER is less
* than MAXITEMS or indicator 03 is on.
C
DOU
COUNTER < MAXITEMS OR *IN03
* The operations controlled by the IF operation will occur if
* DUEDATE (a date variable) is an earlier date than
* December 31, 1994.
C
IF
DUEDATE < D'12-31-94'
* In this numeric expression, COUNTER is assigned the value
* of COUNTER plus 1.
C
EVAL
COUNTER = COUNTER + 1
* This numeric expression uses a built-in function to assign the number
* of elements in the array ARRAY to the variable ARRAYSIZE.
C
EVAL
ARRAYSIZE = %ELEM(ARRAY)
* This expression calculates interest and performs half adjusting on
* the result which is placed in the variable INTEREST.
C
EVAL (H) INTEREST = BALANCE * RATE
*
*
*
*
*
*
*
*
|
C
C
C
This character expression builds a sentence from a name and a
number using concatentation. Since you can not concatenate
numeric data, you must use %CHAR, %EDITC, %EDITW or %EDITFLT to convert
to character data.
Note that no continuation character is needed to continue the
expression. The final + on the first line is a concatenation
operator, not a continuation character.
This statement produces 'Id number for John Smith is 231 364'
EVAL
STRING = 'Id number for ' +
%TRIMR(First) + ' '+ %TRIMR(Last)
+ ' is ' + %EDITW(IdNum : '
&
')
Figure 175. Expression Examples
General Expression Rules
The following are general rules that apply to all expressions:
1. Expressions are coded in the Extended-Factor 2 entry on the Calculation Specification.
2. An expression can be continued on more than one specification. On a continuation specification, the only entries allowed are C in column 6 and the
Extended-Factor 2 entry.
No special continuation character is needed unless the expression is split within
a literal or a name.
3. Blanks (like parentheses) are required only to resolve ambiguity. However, they
may be used to enhance readability.
|
|
Note that RPG will read as many characters as possible when parsing each
token of an expression. For example,
¹ X**DAY is X raised to the power of DAY
|
412
ILE RPG for AS/400 Reference
Expression Operators
|
¹ X* *DAY is X multiplied by *DAY
4. The TRUNCNBR option (as a command parameter or as a keyword on a
control specification) does not apply to calculations done within expressions.
When overflow occurs during an expression operation, an exception is always
issued.
Expression Operands
An operand can be any field name, named constant, literal, or prototyped procedure returning a value. In addition, the result of any operation can also be used as
an operand to another operation. For example, in the expression A+B*21, the result
of B*21 is an operand to the addition operation.
Expression Operators
There are several types of operations:
Unary Operations
Unary operations are coded by specifying the operation followed by one
operand. The unary operations are:
+
The unary plus operation maintains the value of the numeric
operand.
-
The unary minus operation negates the value of the numeric
operand. For example, if NUMBER has the value 123.4, the
value of -NUMBER is -123.4.
NOT
The logical negation operation returns '1' if the value of the
indicator operand is '0' and '0' if the indicator operand is '1'.
Note that the result of any comparison operation or operation
AND or OR is a value of type indicator.
Binary Operations
Binary operations are coded by specifying the operation between the
two operands. The binary operations are:
+
The meaning of this operation depends on the types of the
operands. It can be used for:
1. Addition of two numeric values
|
|
2. Concatenation of two character, two graphic, or two
UCS-2 values
3. Adding a numeric offset to a basing pointer
-
The meaning of this operation depends on the types of the
operands. It can be used for:
1. Subtracting two numeric values
2. Subtracting a numeric offset from a basing pointer
3. Subtracting two pointers
*
The multiplication operation is used to multiply two numeric
values.
/
The division operation is used to divide two numeric values.
Chapter 21. Expressions
413
Operation Precedence
**
The exponentiation operation is used to raise a number to
the power of another. For example, the value of 2**3 is 8.
=
The equality operation returns '1' if the two operands are
equal, and '0' if not.
<>
The inequality operation returns '0' if the two operands are
equal, and '1' if not.
>
The greater than operation returns '1' if the first operand is
greater than the second.
>=
The greater than or equal operation returns '1' if the first
operand is greater or equal to the second.
<
The less than operation returns '1' if the first operand is less
than the second.
<=
The less than or equal operation returns '1' if the first
operand is less or equal to the second.
AND
The logical and operation returns returns '1' if both operands
have the value of indicator '1'.
OR
The logical or operation returns returns '1' if either operand
has the value of indicator '1'.
Built-In Functions
Built-in functions are discussed in Chapter 20, “Built-in Functions” on
page 357.
User-Defined Functions
Any prototyped procedure that returns a value can be used within an
expression. The call to the procedure can be placed anywhere that a
value of the same type as the return value of the procedure would be
used. For example, assume that procedure MYFUNC returns a character value. The following shows three calls to MYFUNC:
C
C
C
IF
EVAL
ENDIF
MYFUNC(string1) = %TRIM(MYFUNC(string2))
%subst(X:3) = MYFUNC('abc')
Figure 176. Using a Prototyped Procedure in an Expression
For more information on user-defined functions see Chapter 6,
“Subprocedures” on page 91.
Operation Precedence
The precedence of operations determines the order in which operations are performed within expressions. High precedence operations are performed before lower
precedence operations.
Since parentheses have the highest precedence, operations within parentheses are
always performed first.
Operations of the same precedence (for example A+B+C) are evaluated in left to
right order, except for **, which is evaluated from right to left.
414
ILE RPG for AS/400 Reference
Data Types
(Note that although an expression is evaluated from left to right, this does not mean
that the operands are also evaluated from left to right. See “Order of Evaluation” on
page 425 for additional considerations.)
The following list indicates the precedence of operations from highest to lowest:
1. ()
2. Built-in functions, user-defined functions
3. unary +, unary -, NOT
4. **
5. *, /
6. binary +, binary 7. =, <>, >, >=, <, <=
8. AND
9. OR
Figure 177 shows how precedence works.
*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
*
* The following two operations produce different results although
* the order of operands and operators is the same. Assume that
* PRICE = 100, DISCOUNT = 10, and TAXRATE = 0.15.
* The first EVAL would result in a TAX of 98.5.
* Since multiplication has a higher precedence than subtraction,
* DISCOUNT * TAXRATE is the first operation performed. The result
* of that operation (1.5) is then subtracted from PRICE.
C
EVAL
*
*
*
*
C
TAX = PRICE - DISCOUNT * TAXRATE
The second EVAL would result in a TAX of 13.50.
Since parentheses have the highest precedence the operation
within parenthesis is performed first and the result of that
operation (90) is then multiplied by TAXRATE.
EVAL
TAX = (PRICE - DISCOUNT) * TAXRATE
Figure 177. Precedence Example
Data Types
All data types are allowed within expressions. However, specific operations only
support certain data types as operands. For example, the * operation only allows
numeric values as operands. Note that the relational and logical operations return a
value of type indicator, which is a special type of character data. As a result, any
relational or logical result can be used as an operand to any operation that expects
character operands.
Chapter 21. Expressions
415
Data Types
Data Types Supported by Expression Operands
Table 32 describes the type of operand allowed for each unary operator and the
type of the result. Table 33 describes the type of operands allowed for each binary
operator and the type of the result. Table 34 on page 417 describes the type of
operands allowed for each built-in function and the type of the result. Prototyped
procedures support whatever data types are defined in the prototype definition.
Table 32. Types Supported for Unary Operations
Operation
Operand Type
Result Type
- (negation)
Numeric
Numeric
+
Numeric
Numeric
NOT
Indicator
Indicator
Table 33. Operands Supported for Binary Operations
|
Operator
Operand 1 Type
Operand 2 Type
Result Type
+ (addition)
Numeric
Numeric
Numeric
- (subtraction)
Numeric
Numeric
Numeric
* (multiplication)
Numeric
Numeric
Numeric
/ (division)
Numeric
Numeric
Numeric
** (exponentiation)
Numeric
Numeric
Numeric
+ (concatenation)
Character
Character
Character
+ (concatenation)
Graphic
Graphic
Graphic
+ (concatenation)
UCS-2
UCS-2
UCS-2
+ (add offset to pointer)
Basing Pointer
Numeric
Basing Pointer
- (subtract pointers)
Basing Pointer
Basing Pointer
Numeric
- (subtract offset from
pointer)
Basing Pointer
Numeric
Basing Pointer
Note: For the following operations the operands may be of any type, but the two operands must be of the same
type.
= (equal to)
Any
Any
Indicator
>= (greater than or equal
to)
Any
Any
Indicator
> (greater than)
Any
Any
Indicator
<= (less than or equal to)
Any
Any
Indicator
< (less than)
Any
Any
Indicator
<> (not equal to)
Any
Any
Indicator
AND (logical and)
Indicator
Indicator
Indicator
OR (logical or)
Indicator
Indicator
Indicator
416
ILE RPG for AS/400 Reference
Data Types
Table 34 (Page 1 of 2). Types Supported for Built-in Functions
|
|
Operation
Operands
Result Type
%ABS
Numeric
Numeric
%CHAR
Graphic, Numeric, UCS-2, Date, Time or Timestamp
Character
%DEC
Numeric {: Numeric constant : Numeric constant}
Numeric (packed)
%DECH
Numeric : Numeric constant : Numeric constant
Numeric (packed)
%DECPOS
Numeric
Numeric (unsigned)
%DIV
Numeric : Numeric
Numeric
%EDITC
Non-float Numeric : Character Constant of Length 1
{:*CURSYM | *ASTFILL | character currency symbol}
Character (fixed length)
%EDITFLT
Numeric
Character (fixed length)
%EDITW
Non-float Numeric : Character Constant
Character (fixed length)
%EOF
{File name}
Indicator
%EQUAL
{File name}
Indicator
%ERROR
|
Indicator
%FLOAT
Numeric
Numeric (float)
%FOUND
{File name}
Indicator
%GRAPH
Character, Graphic, or UCS-2 {: ccsid}
Graphic
%INT
Numeric
Numeric (integer)
%INTH
Numeric
Numeric (integer)
%LEN
Any
Numeric (unsigned)
%OPEN
File name
Indicator
%PARMS
|
|
|
Numeric (integer)
%REM
Numeric : Numeric
Numeric
%REPLACE
Character : Character {: Numeric {: Numeric}}
Character
%REPLACE
Graphic : Graphic {: Numeric {: Numeric}}
Graphic
%REPLACE
UCS-2 : UCS-2 {: Numeric {: Numeric}}
UCS-2
%SCAN
Character : Character {: Numeric}
Numeric (unsigned)
%SCAN
Graphic : Graphic {: Numeric}
Numeric (unsigned)
%SCAN
UCS-2 : UCS-2 {: Numeric}
Numeric (unsigned)
%STATUS
{File name}
Numeric (zoned decimal)
%STR
Basing Pointer {: Numeric}
Character
Note: When %STR appears on the left-hand side of an expression, the second operand is required.
|
|
%SUBST
Character : Numeric {: Numeric}
Character
%SUBST
Graphic : Numeric {: Numeric}
Graphic
%SUBST
UCS-2 : Numeric {: Numeric}
UCS-2
%TRIM
Character
Character
%TRIM
Graphic
Graphic
%TRIM
UCS-2
UCS-2
%TRIML
Character
Character
%TRIML
Graphic
Graphic
Chapter 21. Expressions
417
Data Types
Table 34 (Page 2 of 2). Types Supported for Built-in Functions
Operation
Operands
Result Type
%TRIML
UCS-2
UCS-2
%TRIMR
Character
Character
%TRIMR
Graphic
Graphic
|
%TRIMR
UCS-2
UCS-2
|
%UCS2
Character, Graphic, or UCS-2 {: ccsid}
Varying length UCS-2 value
%UNS
Numeric
Numeric (unsigned)
%UNSH
Numeric
Numeric (unsigned)
%XFOOT
Numeric
Numeric
|
|
Note: For the following built-in functions, arguments must be literals, named constants or variables.
%PADDR
Character
Procedure pointer
%SIZE
Any {: *ALL}
Numeric (unsigned)
Note: For the following built-in functions, arguments must be variables. However, if an array index is specified, it
may be any valid numeric expression.
%ADDR
Any
Basing pointer
%ELEM
Any
Numeric (unsigned)
%NULLIND
Any
Indicator
Format of Numeric Intermediate Results
For binary operations involving numeric fields, the format of the intermediate result
depends on the format of the operands.
For the operators +, -, and *:
¹ If at least one operand has a float format, then the result is float format.
¹ Otherwise, if at least one operand has packed-decimal, zoned-decimal, or
binary format, then the result has packed-decimal format.
¹ Otherwise, if both operands have either integer or unsigned format, then
|
|
– if the operator is -, the result will be integer
|
– otherwise, if both operands are unsigned, the result will be unsigned
|
– otherwise, the result will be integer.
¹ A numeric literal of 10 digits or less and 0 decimal positions is assumed to be
in integer or unsigned format when possible, depending on whether it is a negative or positive number.
For the / operator:
If one operand is float, then the result is float. Otherwise the result is packeddecimal.
418
ILE RPG for AS/400 Reference
Precision Rules for Numeric Operations
For the ** operator:
The result is represented in float format.
Precision Rules for Numeric Operations
Unlike the fixed-form operation codes where you must always specify the result of
each individual operation, RPG must determine the format and precision of the
result of each operation within an expression.
If an operation has a result of format float, integer, or unsigned the precision is the
maximum size for that format. Integer and unsigned operations produce 4-byte
values and float operations produce 8-byte values.
However, if the operation has a packed-decimal, zoned decimal, or binary format,
the precision of the result depends on the precisions of the operands.
It is important to be aware of the precision rules for decimal operations since even
a relatively simple expression may have a result that may not be what you expect.
For example, if the two operands of a multiplication are large enough, the result of
the multiplication will have zero decimal places. If you are multiplying two 20 digit
numbers, ideally you would need a 40 digit result to hold all possible results of the
multiplication. However, since RPG supports numeric values only up to 30 digits,
the result is adjusted to 30 digits. In this case, as many as 10 decimal digits are
dropped from the result.
There are two sets of precision rules that you can use to control the sizes of intermediate values:
1. The default rules give you intermediate results that are as large as possible in
order to minimize the possibility of numeric overflow. Unfortunately, in certain
cases, this may yield results with zero decimal places if the result is very large.
2. The "Result Decimal Positions" precision rule works the same as the default
rule except that if the statement involves an assignment to a numeric variable
or a conversion to a specific decimal precision, the number of decimal positions
of any intermediate result is never reduced below the desired result decimal
places.
In practice, you don't have to worry about the exact precisions if you examine
the compile listing when coding numeric expressions. A diagnostic message
indicates that decimal positions are being dropped in an intermediate result. If
there is an assignment involved in the expression, you can ensure that the
decimal positions are kept by using the "Result Decimal Positions" precision
rule for the statement by coding operation code extender (R).
If the "Result Decimal Position" precision rule cannot be used (say, in a relational expression), built-in function %DEC can be used to convert the result of a
sub-expression to a smaller precision which may prevent the decimal positions
from being lost.
Chapter 21. Expressions
419
Precision Rules for Numeric Operations
Using the Default Precision Rules
Using the default precision rule, the precision of a decimal intermediate in an
expression is computed to minimize the possibility of numeric overflow. However, if
the expression involves several operations on large decimal numbers, the intermediates may end up with zero decimal positions. (Especially, if the expression has
two or more nested divisions.) This may not be what the programmer expects,
especially in an assignment.
When determining the precision of a decimal intermediate, two steps occur:
1. The desired or "natural" precision of the result is computed.
2. If the natural precision is greater than 30 digits, the precision is adjusted to fit in
30 digits. This normally involves first reducing the number of decimal positions,
and then if necessary, reducing the total number of digits of the intermediate.
This behaviour is the default and can be specified for an entire module (using
control specification keyword EXPROPTS(*MAXDIGITS) or for single free-form
expressions (using operation code extender M).
Precision of Intermediate Results
Table 35 describes the default precision rules in more detail.
Table 35 (Page 1 of 2). Precision of Intermediate Results
Operation
Result Precision
Note: The following operations produce a numeric result. L1 and L2 are the number of
digits of the two operands. Lr is the number of digits of the result. D1 and D2 are
the number of decimal places of the two operands. Dr is the number of decimal
places of the result. T is a temporary value.
N1+N2
T=min (max (L1-D1, L2-D2)+1, 30)
Dr=min (max (D1,D2), 30-t)
Lr=t+Dr
N1-N2
T=min (max (L1-D1, L2-D2)+1, 30)
Dr=min (max (D1,D2), 30-t)
Lr=t+Dr
N1*N2
Lr=min (L1+L2, 30)
Dr=min (D1+D2, 30-min ((L1-D1)+(L2-D2), 30))
N1/N2
Lr=30
Dr=max (30-((L1-D1)+D2), 0)
N1**N2
Double float
Note: The following operations produce a character result. Ln represents the length of
the operand in number of characters.
|
C1+C2
Lr=min(L1+L2,65535)
Note: The following operations produce a DBCS result. Ln represents the length of the
operand in number of DBCS characters.
D1+D2
Lr=min(L1+L2,16383)
Note: The following operations produce a result of type character with subtype indicator. The result is always an indicator value (1 character).
420
ILE RPG for AS/400 Reference
Precision Rules for Numeric Operations
Table 35 (Page 2 of 2). Precision of Intermediate Results
Operation
Result Precision
V1=V2
1 (indicator)
V1>=V2
1 (indicator)
V1>V2
1 (indicator)
V1<=V2
1 (indicator)
V1<V2
1 (indicator)
V1<>V2
1 (indicator)
V1 AND V2
1 (indicator)
V1 OR V2
1 (indicator)
Example of Default Precision Rules
This example shows how the default precision rules work.
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++
D FLD1
S
15P 4
D FLD2
S
15P 2
D FLD3
S
5P 2
D FLD4
S
9P 4
D FLD5
S
9P 4
CL0N01Factor1+++++++Opcode(E)+Extended-factor2+++++++++++++++++++++++++++
C
EVAL
FLD1 = FLD2/(((FLD3/100)*FLD4)+FLD5)
(
.1/ )
(
.2/
)
(
.3/
)
(
.4/
)
Figure 178. Precision of Intermediate Results
When the above Calculation specification is processed, the resulting value assigned
to FLD1 will have a precision of zero decimals, not the four decimals expected. The
reason is that when it gets to the last evaluation (.4/ in the above example), the
number to which the factor is scaled is negative. To see why, look at how the
expression is evaluated.
.1/
Evaluate FLD3/100
Rules:
Lr = 30
Dr = max(30-((L1-D1)+D2),0)
= max(30-((5-2)+0),0)
= max(30-3,0)
= 27
.2/
Evaluate (Result of 1 * FLD4)
Rules:
Chapter 21. Expressions
421
Precision Rules for Numeric Operations
Lr =
=
=
Dr =
=
=
=
=
.3/
min(L1+L2,30)
min(30+9,30)
30
min(D1+D2,30-min((L1-D1)+(L2-D2),30))
min(27+4,30-min((30-27)+(9-4),30))
min(31,30-min(3+5,30)
min(31,30-8)
22
Evaluate (Result of 2 + FLD5)
Rules:
T
=
=
=
=
=
Dr =
=
=
=
Lr =
=
.4/
min(max(L1-D1,L2-D2)+1,30)
min(max(30-22,9-4)+1,30)
min(max(8,5)+1,30)
min(9,30)
9
min(max(D1,D2),30-T)
min(max(22,4),30-9)
min(22,21)
21
T + Dr
9 + 21 = 30
Evaluate FLD2/Result of 3
Rules:
Lr = 30
Dr = max(30-((L1-D1)+D2),0)
= max(30-((15-2)+ 21),0)
= max(30-(13+21),0)
= max(-4,0)
**** NEGATIVE NUMBER TO WHICH FACTOR IS SCALED
= 0
****
To avoid this problem, you can change the above expression so that the first evaluation is a multiplication rather than a division, that is, FLD3 * 0.01 or use the %DEC
built-in function to set the sub-expression FLD3/100: %DEC(FLD3/100 : 15 : 4) or
use operation extender (R) to ensure that the number of decimal positions never
falls below 4.
Using the "Result Decimal Position" Precision Rules
The "Result Decimal Position" precision rule means that the precision of a decimal
intermediate will be computed such that the number of decimal places will never be
reduced smaller than the number of decimal positions of the result of the assignment. This is specified by:
1.
EXPROPTS(*RESDECPOS) on the Control Specification. Use this to specify
this behaviour for an entire module.
2. Operation code extender R specified for a free-form operation.
Result Decimal Position rules apply in the following circumstances:
1. Result Decimal Position precision rules apply only to packed decimal intermediate results. This behaviour does not apply to the intermediate results of operations that have integer, unsigned, or float results.
2. Result Decimal Position precision rules apply only where there is an assignment (either explicit or implicit) to a decimal target (packed, zoned, or binary).
This can occur in the following situations:
422
ILE RPG for AS/400 Reference
Precision Rules for Numeric Operations
a. For an EVAL statement, the minimum decimal places is given by the
decimal positions of the target of the assignment and applies to the
expression on the right-hand side of the assignment. If half-adjust also
applies to the statement, one extra digit is added to the minimum decimal
positions (provided that the minimum is less than 30).
b. For a RETURN statement, the minimum decimal places is given by the
decimal positions of the return value defined on the PI specification for the
procedure. If half-adjust also applies to the statement, one extra digit is
added to the minimum decimal positions (provided that the minimum is less
than 30).
c. For a VALUE or CONST parameter, the minimum decimal positions is
given by the decimal positions of the formal parameter (specified on the
procedure prototype) and applies to the expression specified as the passed
parameter.
d. For built-in function %DEC and %DECH with explicit length and decimal
positions specified, the minimum decimal positions is given by the third
parameter of the built-in function and applies to the expression specified as
the first parameter.
The minimum number of decimal positions applies to the entire sub-expression
unless overridden by another of the above operations. If half-adjust is specified
(either as the H operation code extender, or by built-in function %DECH), the
number of decimal positions of the intermediate result is never reduced below
N+1, where N is the number of decimal positions of the result.
3. The Result Decimal Position rules do not normally apply to conditional
expressions since there is no corresponding result. (If the comparisons must be
performed to a particular precision, then %DEC or %DECH must be used on
the two arguments.)
On the other hand, if the conditional expression is embedded within an
expression for which the minimum decimal positions are given (using one of the
above techniques), then the Result Decimal Positions rules do apply.
Example of "Result Decimal Position" Precision Rules
The following examples illustrate the "Result Decimal Position" precision rules:
Chapter 21. Expressions
423
Short Circuit Evaluation
* This example shows the precision of the intermediate values
* using the two precision rules.
D
D
D
D
D
D
D
D
D
D
p1
p2
p3
p4
s1
s2
i1
f1
proc
parm1
s
s
s
s
s
s
s
s
pr
13p
13p
13p
15p
13s
13s
10i
8f
8p
20p
2
2
2
9
2
2
0
0
3
5 value
* In the following examples, for each sub-expression,
* two precisions are shown. First, the natural precision,
* and then the adjusted precision.
* Example 1:
C
* p1*p2
* p1*p2*p3
C
* p1*p2
* p1*p2*p3
*
C
* p1*p2
* p1*p2*p3
*
eval
p1 = p1 * p2 * p3
-> P(26,4); P(26,4)
-> P(39,6); P(30,0) (decimal positions are truncated)
eval(r)
p1 = p1 * p2 * p3
-> P(26,4); P(26,4)
-> P(39,6); P(30,2) (decimal positions do not drop
below target decimal positions)
eval(rh) p1 = p1 * p2 * p3
-> P(26,4); P(26,5)
-> P(39,6); P(30,3) (decimal positions do not drop
below target decimals + 1)
* Example 2:
C
*
*
*
*
p1*p2
s1*s2
s1*s2*p4
p1*p2*proc()
->
->
->
->
p1*p2
s1*s2
s1*s2*p4
p1*p2*proc()
->
->
->
->
C
*
*
*
*
*
eval
p4 = p1 * p2 * proc (s1*s2*p4)
P(26,4); P(26,4)
P(26,4); P(26,4)
P(41,13); P(30,2) (decimal positions are truncated)
P(34,7); P(30,3) (decimal positions are truncated)
eval(r)
p4 = p1 * p2 * proc (s1*s2*p4)
P(26,4); P(26,4)
P(26,4); P(26,4)
P(41,13); P(30,5)
P(34,7); P(30,7) (we keep all decimals since we are
already below target decimals)
Figure 179. Examples of Precision Rules
Short Circuit Evaluation
Relational operations AND and OR are evaluated from left to right. However, as
soon as the value is known, evaluation of the expression stops and the value is
returned. As a result, not all operands of the expression need to be evaluated.
424
ILE RPG for AS/400 Reference
Order of Evaluation
For operation AND, if the first operand is false, then the second operand is not
evaluated. Likewise, for operation OR, if the first operand is true, the second
operand is not evaluated.
There are two implications of this behaviour. First, an array index can be both
tested and used within the same expression. The expression
I<=%ELEM(ARRAY) AND I>0 AND ARRAY(I)>10
will never result in an array indexing exception.
The second implication is that if the second operand is a call to a user-defined
function, the function will not be called. This is important if the function changes the
value of a parameter or a global variable.
Order of Evaluation
The order of evaluation of operands within an expression is not guaranteed. Therefore, if a variable is used twice anywhere within an expression, and there is the
possibility of side effects, then the results may not be the expected ones.
For example, consider the source shown in Figure 180, where A is a variable, and
FN is a procedure that modifies A. There are two occurrences of A in the
expression portion of the second EVAL operation. If the left-hand side (operand
1) of the addition operation is evaluated first, X is assigned the value 17, (5 +
FN(5) = 5 + 12 = 17). If the right-hand side (operand 2) of the addition operation is evaluated first, X is assigned the value 18, (6 + FN(5) = 6 + 12 = 18).
*
A is a variable. FN is procedure that modifies A.
C
EVAL
A = 5
C
EVAL
X = A + FN(A)
P FN
B
D FN
PI
5P 0
D
PARM
5P 0
C
EVAL
PARM = PARM + 1
C
RETURN
2 * PARM
P FN
E
Figure 180. Sample coding of a call with side effects
Chapter 21. Expressions
425
Order of Evaluation
426
ILE RPG for AS/400 Reference
Chapter 22. Operation Codes
The RPG IV programming language allows you to do many different types of operations on your data. Operation codes, which are entered on the calculation specifications, indicate the operation to be done. Usually they are abbreviations of the
name of the operation.
Operation codes can be categorized by function. The first part of this chapter
includes general information about these categories. The latter part of the chapter
describes each operation code in alphabetical order and shows one or more examples for most of the operations.
The tables on the next few pages are a summary of the specifications for each
operation code.
¹ An empty column indicates that the field must be blank.
¹ All underlined fields are required.
¹ An underscored space denotes that there is no resulting indicator in that position.
¹ Symbols
+
−
Plus
Minus
¹ Extenders
(D)
(D)
(E)
(H)
(M)
(N)
(N)
(P)
(R)
(T)
(Z)
Pass operational descriptors on bound call
Date field
Error handling
Half adjust (round the numeric result)
Default precision rules
Do not lock record
Set pointer to *NULL after successful DEALLOC
Pad the result with blanks or zeros
"Result Decimal Position" precision rules
Time field
Timestamp field
¹ Resulting indicator symbols
BL
BN
BOF
EOF
EQ
ER
FD
HI
IN
LO
LR
NR
NU
OF
 Copyright IBM Corp. 1994, 1999
Blank(s)
Blank(s) then numeric
Beginning of the file
End of the file
Equal
Error
Found
Greater than
Indicator
Less than
Last record
No record was found
Numeric
Off
427
ON
Z
ZB
On
Zero
Zero or Blank
Table 36 (Page 1 of 5). Operation Code Specifications Summary
Resulting Indicators
Codes
Factor 1
Factor 2
ACQ (E8)
Device name
WORKSTN file
ADD (H)
Addend
Addend
Sum
ADDDUR (E)
Date/Time
Duration:Duration Code
Date/Time
ER
Length
Pointer
ER
ALLOC (E)
ANDxx
Comparand
BEGSR
Subroutine name
Result Field
75-76
+
−
Z
Comparand
Bit numbers
Character
field
BITON
Bit numbers
Character
field
Comparand
Label
CALL (E)
Program name
CALLB (D E)
Procedure name or Procedure pointer
CALLP (E M/R)
NAME{ (Parm1 {:Parm2...}) }
Comparand
73-74
ER
BITOFF
CABxx
71-72
HI
LO
EQ
Plist name
ER
LR
Plist name
ER
LR
HI
LO
EQ
NR2
ER
CASxx
Comparand
Comparand
Subroutine
name
CAT (P)
Source string 1
Source string 2:number
of blanks
Target string
CHAIN (E N)
Search argument
File name
Data structure
CHECK (E)
Comparator String
Base String:start
Left-most
Position(s)
ER
FD2
CHECKR (E)
Comparator String
Base String:start
Right-most
Position(s)
ER
FD2
CLEAR
*NOKEY
*ALL
Structure or
Variable or
Record
format
CLOSE (E)
File name or *ALL
COMMIT (E)
Boundary
COMP1
Comparand
ER
ER
Comparand
DEALLOC (E/N)
HI
Pointer
DEFINE
*LIKE
Referenced field
Defined field
DEFINE
*DTAARA
External data area
Internal field
DELETE (E)
Search argument
File name
DIV (H)
Dividend
Divisor
428
ILE RPG for AS/400 Reference
Quotient
LO
EQ
ER
NR2
ER
+
−
Z
Table 36 (Page 2 of 5). Operation Code Specifications Summary
Resulting Indicators
Codes
Factor 1
Factor 2
Result Field
DO
Starting value
Limit value
Index value
DOU (M/R)
DOUxx
DOW (M/R)
DSPLY
(E)4
DUMP
73-74
75-76
Indicator expression
Comparand
DOWxx
71-72
Comparand
Indicator expression
Comparand
Comparand
Message identifier
Output queue
Response
ER
Identifier
ELSE
END
Increment value
ENDCS
ENDDO
|
Increment value
ENDFOR
ENDIF
ENDSL
ENDSR
|
|
Label
Return point
EVAL (H M/R)
Result = Expression
EVALR (H M/R)
Result = Expression
EXCEPT
EXCEPT name
EXFMT (E)
Record format name
EXSR
Subroutine name
EXTRCT (E)
Date/Time:Duration Code
FEOD (E)
File name
FOR
Index-name = start-value BY increment TO|DOWNTO limit
FORCE
File name
GOTO
Label
IF (M/R)
Indicator expression
IFxx
Comparand
Comparand
IN (E)
*LOCK
Data area name
ER
Target Field
ER
ER
ER
ITER
KFLD
KLIST
Key field
KLIST name
LEAVE
|
LEAVESR
LOOKUP1
(array)
Search argument
Array name
LOOKUP1
(table)
Search argument
Table name
Table name
HI
LO
EQ7
HI
LO
EQ7
Chapter 22. Operation Codes
429
Table 36 (Page 3 of 5). Operation Code Specifications Summary
Resulting Indicators
Codes
Factor 2
Result Field
MHHZO
Source field
Target field
MHLZO
Source field
Target field
MLHZO
Source field
Target field
MLLZO
Source field
Target field
Source field
Target field
+
−
ZB
Source
Target
+
−
ZB
MOVE (P)
Factor 1
Data Attributes
MOVEA (P)
71-72
73-74
75-76
MOVEL (P)
Data Attributes
Source field
Target field
+
−
ZB
MULT (H)
Multiplicand
Multiplier
Product
+
−
Z
Remainder
+
−
Z
MVR
NEXT (E)
Program device
File name
OCCUR (E)
Occurrence value
Data structure
OPEN (E)
ORxx
ER
Occurrence
value
File name
ER
ER
Comparand
Comparand
OUT (E)
*LOCK
Data area name
PARM
Target field
Source field
Parameter
PLIST
PLIST name
POST (E)3
Program device
File name
INFDS name
ER
READ (E N)
File name, Record name
Data
structure5
ER
EOF6
READC (E)
Record name
ER
EOF6
OTHER
READE (E N)
Search argument
READP (E N)
READPE (E N)
Search argument
REALLOC (E)
File name, Record name
Data
structure5
ER
EOF6
File name, Record name
Data
structure5
ER
BOF6
File name, Record name
Data
structure5
ER
BOF6
Length
Pointer
ER
REL (E)
Program device
File name
RESET (E)
*NOKEY
*ALL
RETURN (H
M/R)
ER
ER
Structure or
Variable or
Record
format
Expression
ROLBK (E)
SCAN (E)
ER
Comparator
string:length
SELECT
430
ER
ILE RPG for AS/400 Reference
Base string:start
Left-most
position(s)
ER
FD2
Table 36 (Page 4 of 5). Operation Code Specifications Summary
Resulting Indicators
Codes
Factor 1
Factor 2
SETGT (E)
Search argument
SETLL (E)
Search argument
Result Field
71-72
73-74
File name
NR2
ER
File name
NR2
ER
EQ7
SETOFF1
OF
OF
OF
SETON1
ON
ON
ON
SHTDN
ON
−
Z
SORTA
Array name
SQRT (H)
Value
Root
SUB (H)
Minuend
Subtrahend
Difference
SUBDUR (E)
(duration)
Date/Time/
Timestamp
Date/Time/Timestamp
Duration:
Duration
Code
ER
SUBDUR (E)
(new date)
Date/Time/
Timestamp
Duration:Duration Code
Date/Time/
Timestamp
ER
SUBST (E P)
Length to extract
Base string:start
Target string
ER
TAG
Label
Date/Time or
Timestamp
Field
ER
TEST (E)9
+
TEST (D E)9
Date Format
Character or
Numeric
field
ER
TEST (E T)9
Time Format
Character or
Numeric
field
ER
TEST (E Z)9
Timestamp Format
Character or
Numeric
field
ER
TESTB1
Bit numbers
75-76
Character
field
OF
ON
EQ
TESTN1
Character
field
NU
BN
BL
TESTZ1
Character
field
AI
JR
XX
TIME
Target field
UNLOCK (E)
Data area, record, or file
name
UPDATE (E)
File name, Record name
WHEN (M/R)
Indicator expression
WHENxx
WRITE (E)
Comparand
ER
Data
structure5
ER
Data
structure5
ER
Comparand
File name, Record name
Chapter 22. Operation Codes
EOF6
431
Arithmetic Operations
Table 36 (Page 5 of 5). Operation Code Specifications Summary
Resulting Indicators
Codes
Factor 1
Factor 2
Result Field
Array name
Sum
String:start
Target String
Z-ADD (H)
Addend
Sum
+
−
Z
Z-SUB (H)
Subtrahend
Difference
+
−
Z
XFOOT (H)
XLATE (E P)
From:To
71-72
+
73-74
75-76
−
Z
ER
Notes:
1. At least one resulting indicator is required.
2. The %FOUND built-in function can be used as an alternative to specifying an NR or FD resulting indicator.
3. You must specify factor 2 or the result field. You may specify both.
4. You must specify factor 1 or the result field. You may specify both.
5. A data structure is allowed in the result field only when factor 2 contains a program-described file name.
6. The %EOF built-in function can be used as an alternative to specifying an EOF or BOF resulting indicator.
7. The %EQUAL built-in function can be used to test the SETLL and LOOKUP operations.
8. For all operation codes with extender 'E', either the extender 'E' or an ER error indicator can be specified, but
not both.
9. You must specify the extender 'E' or an error indicator for the TEST operation.
Arithmetic Operations
The arithmetic operations are:
¹ “ADD (Add)” on page 469
¹ “DIV (Divide)” on page 513
¹ “MULT (Multiply)” on page 596
¹ “MVR (Move Remainder)” on page 597
¹ “SQRT (Square Root)” on page 659
¹ “SUB (Subtract)” on page 660
¹ “XFOOT (Summing the Elements of an Array)” on page 687
¹ “Z-ADD (Zero and Add)” on page 690
¹ “Z-SUB (Zero and Subtract)” on page 691.
For examples of arithmetic operations, see Figure 181 on page 435.
Remember the following when specifying arithmetic operations:
¹ Arithmetic operations can be done only on numerics (including numeric subfields, numeric arrays, numeric array elements, numeric table elements,
numeric named constants, numeric figurative constants, and numeric literals).
¹ In general, arithmetic operations are performed using the packed-decimal
format. This means that the fields are first converted to packed-decimal format
432
ILE RPG for AS/400 Reference
Arithmetic Operations
prior to performing the arithmetic operation, and then converted back to their
specified format (if necessary) prior to placing the result in the result field.
However, note the following exceptions:
– If all operands are unsigned, the operation will use unsigned arithmetic.
– If all are integer, or integer and unsigned, then the operation will use
integer arithmetic.
– If any operands are float, then the remaining operands are converted to
float.
However, the DIV operation uses either the packed-decimal or float format for
its operations. For more information on integer and unsigned arithmetic, see
“Integer and Unsigned Arithmetic” on page 434.
¹ Decimal alignment is done for all arithmetic operations. Even though truncation
can occur, the position of the decimal point in the result field is not affected.
¹ The result of an arithmetic operation replaces the data that was in the result
field.
¹ An arithmetic operation does not change factor 1 and factor 2 unless they are
the same as the result field.
¹ If you use conditioning indicators with DIV and MVR, it is your responsibility to
ensure that the DIV operation occurs immediately before the MVR operation. If
conditioning indicators on DIV cause the MVR operation to be executed when
the immediately preceding DIV was not executed, then undesirable results may
occur.
¹ For information on using arrays with arithmetic operations, see “Specifying an
Array in Calculations” on page 154.
Ensuring Accuracy
¹ The length of any field specified in an arithmetic operation cannot exceed 30
digits. If the result exceeds 30 digits, digits are dropped from either or both
ends, depending on the location of the decimal point.
¹ The TRUNCNBR option (as a command parameter or as a keyword on a
control specification) determines whether truncation on the left occurs with
numeric overflow or a runtime error is generated. Note that TRUNCNBR does
not apply to calculations performed within expressions. If any overflow occurs
within expressions calculations, a run-time message is issued. In addition,
TRUNCNBR does not apply to arithmetic operations performed in integer or
unsigned format.
¹ Half-adjusting is done by adding 5 (-5 if the field is negative) one position to the
right of the last specified decimal position in the result field. The half adjust
entry is allowed only with arithmetic operations, but not with an MVR operation
or with a DIV operation followed by the MVR operation. Half adjust only affects
the result if the number of decimal positions in the calculated result is greater
than the number of decimal positions in the result field. Half adjusting occurs
after the operation but before the result is placed in the result field. Resulting
indicators are set according to the value of the result field after half-adjusting
has been done. Half adjust is not allowed if the result field is float.
Chapter 22. Operation Codes
433
Arithmetic Operations
Performance Considerations
The fastest performance time for arithmetic operations occurs when all operands
are in integer or unsigned format. The next fastest performance time occurs when
all operands are in packed format, since this eliminates conversions to a common
format.
Integer and Unsigned Arithmetic
For all arithmetic operations (not including those in expressions) if factor 1, factor 2,
and the result field are defined with unsigned format, then the operation is performed using unsigned format. Similarly, if factor 1, factor 2, and the result field are
defined as either integer or unsigned format, then the operation is performed using
integer format. If any field does not have either integer or unsigned format, then the
operation is performed using the default format, packed-decimal.
The following points apply to integer and unsigned arithmetic operations only:
¹ If any of the fields are defined as 4-byte fields, then all fields are first converted
to 4 bytes before the operation is performed.
¹ Integer and unsigned values may be used together in one operation. However,
if either factor 1, factor 2, or the result field is signed, then all unsigned values
are converted to integer. If necessary, unsigned 2-byte values are converted to
4-byte integer values to lessen the chance of numeric overflow.
¹ If a literal has 10 digits or less with zero decimal positions, and falls within the
range allowed for integer and unsigned fields, then it is loaded in integer or
unsigned format, depending on whether it is a negative or positive value
respectively.
Note: Integer or unsigned arithmetic may give better performance. However, the
chances of numeric overflow may be greater when using either type of arithmetic.
Arithmetic Operations Examples
434
ILE RPG for AS/400 Reference
Bit Operations
*...1....+....2....+....3....+....4....+....5....+....6....+....7...
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....Comments
C*
C*
In the following example, the initial field values are:
C*
C*
A = 1
C*
B = 10.0
C*
C = 32
C*
D = -20
C*
E = 6
C*
F = 10.0
C*
G = 2.77
C*
H = 70
C*
J = .6
C*
K = 25
C*
L = 1.0, 1.7, -1.1
Result:
C*
C
ADD
1
A
3 0
A = 002
C
B
ADD
C
V
5 2
V = 042.00
C
B
ADD
D
V
V = -10.00
C
Z-ADD
C
V
V = 032.00
C
SUB
1
E
3 0
E = 005
C
C
SUB
B
W
5 1
W = 0022.0
C
C
SUB
D
W
W = 0052.0
C
Z-SUB
C
W
W = -0032.0
C
MULT
E
F
3 0
F = 060
C
B
MULT
G
X
8 4
X = 0027.7000
C
B
MULT
D
X
X = -0200.0000
C
DIV
B
H
3 0
H = 007
C
C
DIV
J
Y
6 2
Y = 0053.33
C
MVR
Z
5 3
Z = 00.002
C
SQRT
K
Z
Z = 05.000
C
XFOOT
L
Z
Z = 01.600
Figure 181. Summary of Arithmetic Operations
Array Operations
The array operations are:
¹ “LOOKUP (Look Up a Table or Array Element)” on page 559
¹ “MOVEA (Move Array)” on page 580
¹ “SORTA (Sort an Array)” on page 657
¹ “XFOOT (Summing the Elements of an Array)” on page 687.
While many operations work with arrays, these operations perform specific array
functions. See each operation for an explanation of its function.
Bit Operations
The bit operations are:
¹ “BITOFF (Set Bits Off)” on page 475
¹ “BITON (Set Bits On)” on page 476
¹ “TESTB (Test Bit)” on page 670.
Chapter 22. Operation Codes
435
Call Operations
The BITOFF and BITON operations allow you to turn off and on specific bits in a
field specified in the result field. The result field must be a one-position character
field.
The TESTB operation compares the bits identified in factor 2 with the corresponding bits in the field named as the result field.
The bits in a byte are numbered from left to right. The left most bit is bit number 0.
In these operations, factor 2 specifies the bit pattern (bit numbers) and the result
field specifies a one-byte character field on which the operation is performed. To
specify the bit numbers in factor 2, a 1-byte hexadecimal literal or a 1-byte character field is allowed. The bit numbers are indicated by the bits that are turned on
in the literal or the field. Alternatively, a character literal which contains the bit
numbers can also be specified in factor 2.
Branching Operations
The branching operations are:
¹ “CABxx (Compare and Branch)” on page 478
¹ “GOTO (Go To)” on page 544
¹ “ITER (Iterate)” on page 551
¹ “LEAVE (Leave a Do/For Group)” on page 556
¹ “TAG (Tag)” on page 667.
The GOTO operation (when used with a TAG operation) allows branching. When a
GOTO operation occurs, the program branches to the specified label. The label can
be specified before or after the GOTO operation. The label is specified by the TAG
or ENDSR operation.
The TAG operation names the label that identifies the destination of a GOTO or
CABxx operation.
The ITER operation transfers control from within a DO-group to the ENDDO statement of the DO-group.
The LEAVE operation is similar to the ITER operation; however, LEAVE transfers
control to the statement following the ENDDO operation.
See each operation for an explanation of its function.
Call Operations
The call operations are:
¹ “CALL (Call a Program)” on page 480
¹ “CALLB (Call a Bound Procedure)” on page 481
¹ “CALLP (Call a Prototyped Procedure or Program)” on page 482
¹ “PARM (Identify Parameters)” on page 608
¹ “PLIST (Identify a Parameter List)” on page 611
¹ “RETURN (Return to Caller)” on page 637.
436
ILE RPG for AS/400 Reference
Call Operations
CALLP is one type of prototyped call. The second type is a call from within an
expression. A prototyped call is a call for which there is a prototype defined for
the call interface.
Call operations allow an RPG IV procedure to transfer control to other programs or
procedures. However, prototyped calls differ from the CALL and CALLB operations
in that they allow free-form syntax.
The RETURN operation transfers control back to the calling program or procedure
and returns a value, if any. The PLIST and PARM operations can be used with the
CALL and CALLB operations to indicate which parameters should be passed on the
call. With a prototyped call, you pass the parameters on the call.
The recommended way to call a program or procedure (written in any language) is
to code a prototyped call.
Prototyped Calls
With a prototyped call, you can call (with the same syntax):
¹ Programs that are on the system at run time
¹ Exported procedures in other modules or service programs that are bound in
the same program or service program
¹ Subprocedures in the same module
A prototype must be included in the definition specifications of the program or procedure making the call. It is used by the compiler to call the program or procedure
correctly, and to ensure that the caller passes the correct parameters.
When a program or procedure is prototyped, you do not need to know the names
of the data items used in the program or procedure; only the number and type of
parameters.
Prototypes improve the communication between programs or procedures. Some
advantages of using prototyped calls are:
¹ The syntax is simplified because no PARM or PLIST operations are required.
¹ For some parameters, you can pass literals and expressions.
¹ When calling procedures, you do not have to remember whether operational
descriptors are required.
¹ The compiler helps you pass enough parameters, of the the correct type,
format and length, by giving an error at compile time if the call is not correct.
¹ The compiler helps you pass parameters with the correct format and length for
some types of parameters, by doing a conversion at run time.
Figure 182 on page 438 shows an example using the prototype ProcName,
passing three parameters. The prototype ProcName could refer to either a program
or a procedure. It is not important to know this when making the call; this is only
important when defining the prototype.
Chapter 22. Operation Codes
437
Call Operations
* The following calls ProcName with the 3
* parameters CharField, 7, and Field2:
C
CALLP
ProcName (CharField: 7: Field2)
Figure 182. Sample of CALLP operation
When calling a procedure in an expression, you should use the procedure name in
a manner consistent with the data type of the specified return value. For example,
if a procedure is defined to return a numeric, then the call to the procedure within
an expression must be where a numeric would be expected.
For more information on calling programs and procedures, and passing parameters,
see the appropriate chapter in the ILE RPG for AS/400 Programmer's Guide. For
more information on defining prototypes and parameters, see “Prototypes and
Parameters” on page 138.
Operational Descriptors
Sometimes it is necessary to pass a parameter to a procedure even though the
data type is not precisely known to the called procedure, (for example, different
types of strings). In these instances you can use operational descriptors to provide
descriptive information to the called procedure regarding the form of the parameter.
The additional information allows the procedure to properly interpret the string. You
should only use operational descriptors when they are expected by the called procedure.
You can request operational descriptors for both prototyped and non-prototyped
parameters. For prototyped parameters, you specify the keyword OPDESC on the
prototype definition. For non-prototyped parameters, you specify (D) as the operation code extender of the CALLB operation. In either case, operational descriptors
are then built by the calling procedure and passed as hidden parameters to the
called procedure.
Parsing Program Names on a Call
Program names are specified in factor 2 of a CALL operation or as the parameter
of the EXTPGM keyword on a prototype. If you specify the library name, it must be
immediately followed by a slash and then the program name (for example,
'LIB/PROG'.). If a library is not specified, the library list is used to find the
program. *CURLIB is not supported.
Note the following rules:
¹ The total length of a literal, including the slash, cannot exceed 12 characters.
¹ The total length of the non-blank data in a field or named constant, including
the slash, cannot exceed 21 characters.
¹ If either the program or the library name exceeds 10 characters, it is truncated
to 10 characters.
The program name is used exactly as specified in the literal, field, named constant,
or array element to determine the program to be called. Specifically:
¹ Any leading or trailing blanks are ignored.
¹ If the first character in the entry is a slash, the library list is used to find the
program.
438
ILE RPG for AS/400 Reference
Call Operations
¹ If the last character in the entry is a slash, a compile-time message will be
issued.
¹ Lowercase characters are not shifted to uppercase.
¹ A name enclosed in quotation marks, for example, '“ABC”', always includes
the quotation marks as part of the name of the program to be called.)
Program references are grouped to avoid the overhead of resolving to the target
program. All references to a specific program using a named constant or literal are
grouped so that the program is resolved to only once, and all subsequent references to that program (by way of named constant or literal only) do not cause a
resolve to recur.
The program references are grouped if both the program and the library name are
identical. All program references by variable name are grouped by the variable
name. When a program reference is made with a variable, its current value is compared to the value used on the previous program reference operation that used that
variable. If the value did not change, no resolve is done. If it did change, a resolve
is done to the new program specified. Note that this rule applies only to references
using a variable name. References using a named constant or literal are never reresolved, and they do not affect whether or not a program reference by variable is
re-resolved. Figure 183 on page 440 illustrates the grouping of program references.
Program CALL Example
Chapter 22. Operation Codes
439
Call Operations
*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....
DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++++++
D Pgm_Ex_A
C
'LIB1/PGM1'
D Pgm_Ex_B
C
'PGM1'
D PGM_Ex_C
C
'LIB/PGM2'
*
*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
C
CALL
Pgm_Ex_A
*
* The following two calls will be grouped together because both
* have the same program name (PGM1) and the same library name
* (none). Note that these will not be grouped with the call using
* Pgm_Ex_A above because Pgm_Ex_A has a different library
* name specified (LIB1).
*
C
CALL
'PGM1'
C
CALL
Pgm_Ex_B
*
* The following two program references will be grouped together
* because both have the same program name (PGM2) and the same
* library name (LIB).
*
C
CALL
'LIB/PGM2'
C
CALL
Pgm_Ex_C
*
*...1....+....2....+....3....+....4....+....5....+....6....+....7...+....
CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq....
*
* The first call in the program using CALLV below will result in
* a resolve being done for the variable CALLV to the program PGM1.
* This is independent of any calls by a literal or named constant
* to PGM1 that may have already been done in the program. The
* second call using CALLV will not result in a resolve to PGM1
* because the value of CALLV has not changed.
*
C
MOVE
'PGM1'
CALLV
21
C
CALL
CALLV
C
CALL
CALLV
Figure 183. Example of Grouping of Program References
Parsing System Built-In Names
When the literal or named constant specified on a bound call starts with "CEE" or
an underscore ('_'), the compiler will treat this as a system built-in. (A bound call
results with either CALLB or with a prototyped call where EXTPGM is not specfied
on the prototype).
If it is not actually a system built-in, then a warning will appear in the listing; you
can ignore this warning.
For more information on APIs, see the System API Reference. To avoid confusion
with system provided APIs, you should not name your procedures starting with
"CEE".
440
ILE RPG for AS/400 Reference
Compare Operations
Value of *ROUTINE
When a call fails, the contents of the *ROUTINE subfield of the program status data
structure (PSDS) is updated with the following:
¹ On an external call, the name of the called program (that is, for CALL or
CALLP to a program).
¹ On a bound static call, the name of the called procedure.
¹ On a bound procedure pointer call, *N.
Note that since the size of this subfield is only 8 bytes long, the name may be
truncated.
Compare Operations
The compare operations are:
¹ “ANDxx (And)” on page 473
¹ “COMP (Compare)” on page 505
¹ “CABxx (Compare and Branch)” on page 478
¹ “CASxx (Conditionally Invoke Subroutine)” on page 485
¹ “DOU (Do Until)” on page 516
¹ “DOUxx (Do Until)” on page 517
¹ “DOW (Do While)” on page 519
¹ “DOWxx (Do While)” on page 520
¹ “IF (If)” on page 546
¹ “IFxx (If)” on page 547
¹ “ORxx (Or)” on page 605
¹ “WHEN (When True Then Select)” on page 681
¹ “WHENxx (When True Then Select)” on page 682
In the ANDxx, CABxx, CASxx, DOUxx, DOWxx, IFxx, ORxx, and WHENxx operations, xx can be:
xx
Meaning
GT
Factor 1 is greater than factor 2.
LT
Factor 1 is less than factor 2.
EQ
Factor 1 is equal to factor 2.
NE
Factor 1 is not equal to factor 2.
GE
Factor 1 is greater than or equal to factor 2.
LE
Factor 1 is less than or equal to factor 2.
Blanks
Unconditional processing (CASxx or CABxx).
The compare operations test fields for the conditions specified in the operations.
These operations do not change the values of the fields. For COMP, CABXX, and
CASXX, the resulting indicators assigned in postions 71 and 76 are set according
Chapter 22. Operation Codes
441
Compare Operations
to the results of the operation. All data types may be compared to fields of the
same data type.
Remember the following when using the compare operations:
¹ If numeric fields are compared, fields of unequal length are aligned at the
implied decimal point. The fields are filled with zeros to the left and/or right of
the decimal point making the field lengths and number of decimal positions
equal for comparison.
¹ All numeric comparisons are algebraic. A plus (+) value is always greater than
a minus (-) value.
¹ Blanks within zoned numeric fields are assumed to be zeros, if the
FIXNBR(*ZONED) control specification keyword or command parameter is used
in the compilation of the program.
¹ If character, graphic, or UCS-2 fields are compared, fields of unequal length are
aligned to their leftmost character. The shorter field is filled with blanks to equal
the length of the longer field so that the field lengths are equal for comparison.
|
¹ Date fields are converted to a common format when being compared.
¹ Time fields are converted to a common format when being compared.
¹ An array name cannot be specified in a compare operation, but an array
element may be specified.
¹ The ANDxx and ORxx operations can be used following DOUxx, DOWxx, IFxx,
and WHENxx.
¹ When comparing a character, graphic, or UCS-2 literal with zero length to a
field (fixed or varying) containing blanks, the fields will compare equal. If you
want to test that a value is of length 0, use the %LEN built-in function. See
Figure 49 on page 121 for examples.
|
442
ILE RPG for AS/400 Reference
Data-Area Operations
Attention!
Note the following points, especially if you want to avoid unpredictable results.
|
|
¹ All graphic and UCS-2 comparisons are done using the hexadecimal representation of the data. The alternate sequence is not used.
¹ If an alternate collating sequence (using the “ALTSEQ{(*NONE | *SRC |
*EXT)}” on page 233 keyword on the Control specification) has been specified for the comparison of character fields, the comparands are converted to
the alternate sequence and then compared. If *HIVAL or *LOVAL is used in
the comparison, the alternate collating sequence may alter the value before
the compare operation. Note that if either comparand is defined with the
ALTSEQ(*NONE) keyword on the definition specification, the alternate collating sequence is not used.
¹
When comparing a basing pointer to *NULL (or to a basing pointer with
value *NULL), the only comparisons that produce predictable results are for
equality and inequality.
¹ Comparing pointers for less-than or greater-than produces predictable
results only when the pointers point to addresses in contiguous storage. For
example, all pointers are set to addresses in one *USRSPC, or all pointers
are set to the addresses of array elements in one array.
¹ When procedure pointer fields are compared for anything except equality or
inequality, the results will be unpredictable.
|
|
¹ Because of the way float values are stored, they should not be compared
for equality or inequality. Instead, the absolute value of the difference
between the two values should be compared with a very small value.
Data-Area Operations
The data-area operations are:
¹ “IN (Retrieve a Data Area)” on page 549
¹ “OUT (Write a Data Area)” on page 607
¹ “UNLOCK (Unlock a Data Area or Release a Record)” on page 677.
The IN and OUT operations allow you to retrieve and write one or all data areas in
a program, depending on the factor 2 entry.
The IN and OUT operations also allow you to control the locking or unlocking of a
data area. When a data area is locked, it can be read but not updated by other
programs or procedures.
The following lock states are used:
¹ For an IN operation with *LOCK specified, an exclusive allow read lock state is
placed on the data area.
¹ For an OUT operation with *LOCK the data area remains locked after the write
operation
¹ For an OUT operation with blank the data area is unlocked after it is updated
Chapter 22. Operation Codes
443
Data-Area Operations
¹ UNLOCK is used to unlock data areas and release record locks, the data areas
and/or records are not updated.
During the actual transfer of data into or out of a data area, there is a systeminternal lock on the data area. If several users are contending for the same data
area, a user may get an error message indicating that the data area is not available.
Remember the following when using the IN, OUT, and UNLOCK operations:
¹ A data-area operation cannot be done on a data area that is not defined to the
operating system.
¹ Before the IN, OUT, and UNLOCK operations can be done on a data area, you
must specify the DTAARA keyword on the definition specification for the data
area, or specify the data area in the result field of an *DTAARA DEFINE statement. (For further information on the DEFINE statement, see “DEFINE (Field
Definition)” on page 508.)
¹ A locked data area cannot be updated or locked by another RPG program;
however, the data area can be retrieved by an IN operation with factor 1 blank.
¹ A data-area name cannot be the name of a multiple-occurrence data structure,
an input record field, an array, an array element, or a table.
¹ A data area cannot be the subfield of a multiple occurrence data structure, a
data-area data structure, a program-status data structure, a file-information data
structure (INFDS), or a data structure that appears on an *DTAARA DEFINE
statement.
A data structure defined with a U in position 23 of the definition specifications indicates that the data structure is a data area. You may specify the DTAARA
keyword for a data area data structure, if specified you can use the IN, OUT and
UNLOCK operation codes to specify further operations for the data area. The data
area is automatically read and locked at program initialization time, and the contents of the data structure are written to the data area when the program ends with
LR on.
To define the local data area (*LDA) you can do one of the following:
¹ Specify the DTAARA(*LDA) keyword on the definition specification for the data
area.
¹ Specify UDS on the definition specification for the data area and leave the
name blank.
¹ Specify *LDA in factor 2 of a *DTAARA DEFINE statement.
To define the *PDA you may specify the DTAARA(*PDA) keyword on the definition
specification for the data area, or specify *PDA in factor 2 of a *DTAARA DEFINE
statement.
444
ILE RPG for AS/400 Reference
Date Operations
Date Operations
Date operations allow you to perform date and time arithmetic, extract portions of a
date, time or timestamp field; or test for valid fields. They operate on date, time,
and timestamp fields, and character and numeric fields representing dates, times
and timestamps. The date operations are:
¹ “ADDDUR (Add Duration)” on page 470
¹ “EXTRCT (Extract Date/Time/Timestamp)” on page 537
¹ “SUBDUR (Subtract Duration)” on page 661
¹ “TEST (Test Date/Time/Timestamp)” on page 668
With “ADDDUR (Add Duration)” on page 470 you can add a duration to a date or
time. With “SUBDUR (Subtract Duration)” on page 661 you can subtract a duration
from a date or time, or calculate the duration between 2 dates, times or
timestamps. With “EXTRCT (Extract Date/Time/Timestamp)” on page 537 you can
extract part of a date, time or timestamp. With “TEST (Test Date/Time/Timestamp)”
on page 668 you can test for a valid date, time, or timestamp field. The valid duration codes (and their short forms) are:
¹ *YEARS for the year (*Y)
¹ *MONTHS for the month (*M)
¹ *DAYS for the day of the month (*D)
¹ *HOURS for the hours (*H)
¹ *MINUTES for the minutes (*MN)
¹ *SECONDS for the seconds (*S)
¹ *MSECONDS for the microseconds (*MS).
Adding or Subtracting Dates
When adding (or subtracting) a duration in months to (or from) a date, the general
rule is that the month portion is increased (or decreased) by the number of months
in the duration, and the day portion is unchanged. The exception to this is when the
resulting day portion would exceed the actual number of days in the resulting
month. In this case, the resulting day portion is adjusted to the actual month end
date.
For example, adding one month to '95/05/30' (*YMD format) results in '95/06/30', as
expected. The resulting month portion has been increased by 1; the day portion is
unchanged. On the other hand, adding one month to '95/05/31' results in '95/06/30'.
The resulting month portion has been increased by 1 and the resulting day portion
has been adjusted because June has only 30 days.
Subtracting one month from '95/03/30' yields '95/02/28'. In this case, the resulting
month portion is decreased by 1 and the resulting day portion adjusted because
February has only 28 days (in non-leap years).
Similar results occur when adding or subtracting a year duration. For example,
adding one year to '92/02/29' results in '93/02/28', an adjusted value since the
resulting year is not a leap year.
Chapter 22. Operation Codes
445
Date Operations
Calculating Durations between Dates
The SUBDUR operation can be used to calculate a duration by subtracting two
dates, times, or timestamps. The result of the calculation is a complete units; any
rounding which is done is downwards. The calculation of durations includes microseconds.
For example, if the actual duration is 384 days, and the result is requested in years,
the result will be 1 complete year because there are 1.05 years in 384 days. A
duration of 59 minutes requested in hours will result in 0 hours. Here are some
additional examples.
|
Table 37. Resulting Durations Using SUBDUR
|
|
Duration
Unit
|
Months
Factor 1
Factor 2
1999-03-28
1999-02-28
1 month
|
1999-03-14
1998-03-15
11 months
|
1999-03-15
1998-03-15
12 months
1999-03-14
1998-03-15
0 years
|
1999-03-15
1998-03-15
1 year
|
1999-03-14-12.34.45.123456
1998-03-14-12.34.45.123457
0 years
1990-03-14-23.00.00.000000
1990-03-14-22.00.00.000001
0 hours
|
Years
|
Hours
Result
Unexpected Results
If adjustment takes place on a date-time addition or subtraction, then a subsequent
duration calculation will most likely result in a different duration than the one originally added or subtracted. This is because the calculated duration will no longer
contain a complete unit, and so, rounding down, will yield one unit less than
expected. This is shown in examples 1 and 2 below.
A second unexpected result can be seen in examples 3 and 4. Different initial dates
give the same result after adding 1 month. When subtracting 1 month from the
result, it is impossible to arrive at both initial dates.
1.
2.
'95/05/31' ADDDUR 1:*MONTH
gives '95/06/30'
'95/06/30' SUBDUR '95/05/31' gives 0 months
You might expect the result of the SUBDUR to be 1 month.
'95/06/30' ADDDUR 1:*MONTH
'95/07/30' SUBDUR '95/06/30'
gives '95/07/30'
gives 1 month
This is the "expected" result.
3.
'95/01/31' ADDDUR 1:*MONTH
'95/01/28' ADDDUR 1:*MONTH
gives '95/02/28'
gives '95/02/28'
Two different dates yield the same date due to adjustment.
4.
'95/02/28' SUBDUR 1:*MONTH
gives '95/01/28'
Reversing the addition does not result in both the original dates.
446
ILE RPG for AS/400 Reference
File Operations
Declarative Operations
The declarative operations do not cause an action to occur (except PARM with
optional factor 1 or 2); they can be specified anywhere within calculations. They are
used to declare the properties of fields or to mark parts of a program. The control
level entry (positions 7 and 8) can be blank or can contain an entry to group the
statements within the appropriate section of the program. The declarative operations are:
¹ “DEFINE (Field Definition)” on page 508
¹ “KFLD (Define Parts of a Key)” on page 553
¹ “KLIST (Define a Composite Key)” on page 554
¹ “PARM (Identify Parameters)” on page 608
¹ “PLIST (Identify a Parameter List)” on page 611
¹ “TAG (Tag)” on page 667.
The DEFINE operation either defines a field based on the attributes (length and
decimal positions) of another field or defines a field as a data area.
The KLIST and KFLD operations are used to indicate the name by which a composite key field may be referred and the fields that compose the composite key. A
composite key is a key that contains a list of key fields. It is built from left to right,
with the first KFLD specified being the leftmost (high-order) field of the composite
key.
The PLIST and PARM operations are used with the CALL and CALLB operations to
allow a called program or procedure access to parameters from a calling program
or procedure.
The TAG operation names the destination of a branching operation such as GOTO
or CABxx.
File Operations
The file operation codes are:
¹ “ACQ (Acquire)” on page 468
¹ “CHAIN (Random Retrieval from a File)” on page 490
¹ “CLOSE (Close Files)” on page 503
¹ “COMMIT (Commit)” on page 504
¹ “DELETE (Delete Record)” on page 512
¹ “EXCEPT (Calculation Time Output)” on page 532
¹ “EXFMT (Write/Then Read Format)” on page 534
¹ “FEOD (Force End of Data)” on page 539
¹ “FORCE (Force a Certain File to Be Read Next Cycle)” on page 543
¹ “NEXT (Next)” on page 598
¹ “OPEN (Open File for Processing)” on page 603
Chapter 22. Operation Codes
447
File Operations
¹ “POST (Post)” on page 613
¹ “READ (Read a Record)” on page 615
¹ “READC (Read Next Changed Record)” on page 618
¹ “READE (Read Equal Key)” on page 620
¹ “READP (Read Prior Record)” on page 623
¹ “READPE (Read Prior Equal)” on page 625
¹ “REL (Release)” on page 629
¹ “ROLBK (Roll Back)” on page 640
¹ “SETGT (Set Greater Than)” on page 646
¹ “SETLL (Set Lower Limit)” on page 650
¹ “UNLOCK (Unlock a Data Area or Release a Record)” on page 677
¹ “UPDATE (Modify Existing Record)” on page 679
¹ “WRITE (Create New Records)” on page 685.
Most file operations can be used with both program described and externally
described files (F or E respectively in position 22 of the file description specifications).
When an externally described file is used with certain file operations, a record
format name, rather than a file name, can be specified in factor 2. Thus, the processing operation code retrieves and/or positions the file at a record format of the
specified type according to the rules of the calculation operation code used.
When the OVRDBF (override with data base file) command is used with the MBR
(*ALL) parameter specified, the SETLL, SETGT and CHAIN operations only
process the current open file member. For more information, refer to the DB2 UDB
for AS/400 Database Programming.
The WRITE and UPDATE operations that specify a program described file name in
factor 2 must have a data structure name specified in the result field. The CHAIN,
READ, READE, READP, and READPE operations that specify a program described
file name in factor 2 may have a data structure name specified in the result field.
With the CHAIN, READ, READE, READP, and READPE operations, data is transferred directly between the file and the data structure, without processing the input
specifications for the file. Thus, no record identifying or field indicators are set on as
a result of an input operation to a data structure. If all input and output operations
to the file have a data structure specified in the result field, input and output specifications are not required.
If an input operation (CHAIN, EXFMT, READ, READC, READE, READP, READPE)
does not retrieve a record because no record was found, because an error
occurred in the operation, or because the last record was already retrieved (end of
file), then no data is extracted and all fields in the program remain unchanged.
If you specify N as the operation extender of a CHAIN, READ, READE, READP, or
READPE operation for an update disk file, a record is read without locking. If no
operation extender is specified, the record is locked if the file is an update disk file.
448
ILE RPG for AS/400 Reference
Information Operations
Exception/errors that occur during file operations can be handled by the programmer (by coding an error indicator or specifying a file-error subroutine), or by
the RPG IV error handler.
Note: Input and output operations in subprocedures involving input and output
specifications always use the global name, even if there is a local variable
of the same name. For example, if the field name TOTALS is defined in the
main source section, as well as in a subprocedure, any input or output operation in the subprocedure will use the field as defined in the main source
section.
See “Database Null Value Support” on page 198 for information on handling files
with null-capable fields.
Indicator-Setting Operations
The indicator setting operations are
¹ “SETOFF (Set Indicator Off)” on page 654
¹ “SETON (Set Indicator On)” on page 655
The SETON and SETOFF operations set (on or off) indicators specified in positions
71 through 76. At least one resulting indicator must be specified in these positions.
Remember the following when setting indicators:
¹ The 1P, MR, KA through KN, and KP through KY indicators cannot be set on
by the SETON operation.
¹ The 1P and MR indicators cannot be set off by the SETOFF operation.
¹ Setting L1 through L9 on or off with a SETON or SETOFF operation does not
set any lower control level indicators.
Information Operations
The information operations are:
¹ “DUMP (Program Dump)” on page 525
¹ “SHTDN (Shut Down)” on page 656
¹ “TIME (Retrieve Time and Date)” on page 675.
The DUMP operation provides a dump of all indicators, fields, data structures,
arrays, and tables used in a program.
The SHTDN operation allows the program to determine whether the system operator has requested shutdown. If so, the resulting indicator that must be specified in
positions 71 and 72 is set on.
The TIME operation allows the program to access the system time of day and
system date at any time during program running.
Chapter 22. Operation Codes
449
Memory Management Operations
Initialization Operations
The initialization operations provide run-time clearing and resetting of all elements
in a structure (record format, data structure, array, or table) or a variable (field, subfield, or indicator).
The initialization operations are:
¹ “CLEAR (Clear)” on page 499
¹ “RESET (Reset)” on page 630.
|
|
|
The CLEAR operation sets all elements in a structure or variable to their default
value depending on the field type (numeric, character, graphic, UCS-2, indicator,
pointer, or date/time/timestamp).
The RESET operation sets all elements in a structure or variable to their initial
values (the values they had at the end of the initialization step in the program
cycle).
The RESET operation is used with data structure initialization and the initialization
subroutine (*INZSR). You can use both data structure initialization and the *INZSR
to set the initial value of a var