Subprocedures in ILE RPG: Scope, Lifetime, and a Visible Contract
EXSR getPrice says nothing at the call site about which fields the subroutine reads or changes. UNITPRC = unitPrice(ITEMNO) says one input, one result. The difference is the reason subprocedures exist.
Anatomy
A subprocedure sits between DCL-PROC and END-PROC. Its procedure interface, DCL-PI, declares the return type and parameters. Local declarations follow, then calculations, and RETURN ends it with a value. Within the same module, no separate prototype is required.
Global and local
Definitions before the first DCL-PROC are global and visible to every procedure. Definitions inside a subprocedure, including parameters, are local. A local name with the same spelling as a global hides it β the compiler accepts this, and the next maintainer pays for it. RPG names are not case-sensitive, so a parameter called itemNo hides a file field called ITEMNO.
Automatic and static
Local variables are automatic: re-initialized on every call. STATIC keeps a value between calls without widening its scope. A static local is state, so document why its value may safely persist.
dcl-s lastItem char(15) static; // one pricing run;
dcl-s lastPrice packed(9:2) static; // prices fixed mid-runThe exceptions to remember
Numbered indicators and *INLR are global. Subroutines coded inside a subprocedure belong only to it. Procedure names are private to the module unless exported. A local file generates no fields β every operation names a result data structure β and closes on return unless declared STATIC.
Three kinds of module
A cycle-main module runs its main source section under the RPG cycle. A linear-main module names its main procedure with CTL-OPT MAIN. A NOMAIN module holds only subprocedures and becomes the building block of service programs.
Lesson 24 closes with an order-pricing program whose main loop reads like the business process, and a PUB400 exercise that inspects a real IBM service program's exported procedures and then builds and runs the pricing program.
Get the lesson
Lesson 24, βProcedures and Subprocedures: Definition and Scope,β is part of Beginner ILE RPG in IBM i ILE RPG Mastery and is available at ILERPG.com for USD 10. The complete Beginner ILE RPG series β all 18 lessons β is USD 180, or USD 135 with coupon code RPG30, which takes 25% off when you purchase the full series.