29
Fri, Nov
0 New Articles

Programming in ILE RPG - Declaring Named Constants

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

The concept of the named constant is closely associated with the concept of a literal. Miss the introduction to using declarations?  Read it here: Part 1

By Brian Meyers and Jim Buck

Editor's Note: This article is excerpted from chapter 4 of Programming in ILE RPG, Fifth Edition.

A literal is a means of noting a fixed value (e.g., a number, a character string, or a date). For example, the number 789 is a literal, as is the character string ‘September’. ILE RPG lets you associate a data name with a literal so that you can reference the literal by its name throughout your program. The resulting data item is a named constant.

Once you’ve defined a named constant, you can use it with any processing appropriate to its type. The value of a named constant is fixed. You cannot change it during the course of program execution.

Named constants let you define constants in one place near the beginning of your program rather than coding them as literals throughout your calculations. This practice is a standard of good programming because it facilitates maintenance programming. If a programmer needs to change a value, such as Taxrate, it is much easier and less error-prone to locate the named constant and change its value in that one place rather than having to search through an entire program looking for and examining the purpose of every calculation in which the literal value .0765 occurs.

Before we examine how to declare named constants, let’s dig a little deeper into literals.

Numeric Literals

A numeric literal is a number, and its value remains fixed throughout the program (unlike a variable, whose value can change throughout the program). A literal can contain a radix character or a sign, or both. If the numeric literal includes a sign, the sign must be the leftmost character of the literal. If the numeric literal does not include a sign, the computer assumes that the literal represents a positive number.

Other than a radix character and a sign, a literal can contain only the digits 0 through 9. Never use blanks, currency symbols, percent signs, or thousands separators in numeric literals, and do not enclose them in apostrophes ('). The numeric value can be as long as 63 digits, with up to 63 decimal positions. Some examples of valid numeric literals follow:

Programming in ILE RPG: Declaring Named Constants - Figure 1

Character Literals

Often, you will want to work with character values as well with as numeric values. RPG lets you use character literals for that purpose. Character literals are character strings. Like numeric literals, character literals maintain a constant value during the execution of the program. To indicate that a value is a character literal (and not a variable name),

simply enclose it within apostrophes. No restriction applies on what characters can make up the literal. Any character that you can represent via the keyboard—including a blank— is acceptable. If the literal is to include an apostrophe character, use two apostrophes to represent it. Character literals can be up to 16,380 bytes. Some examples of character literals follow:

Programming in ILE RPG: Declaring Named Constants - Figure 2

Tip

You cannot use a character literal enclosed in apostrophes with an arithmetic operation even if all the characters of the literal are digits. Numeric literals are not enclosed within apostrophes.

Typed Literals

In addition to numeric and character literals, you can express other data values, such as dates and times, by using typed literals. To code a typed literal, enclose the value within apostrophes and precede it with a data type code to indicate which data type the literal represents. To refer to a value of January 1, 2018, for example, you’d code D'2018-01-01' as the literal. Other common data type codes for literals are T (for times), Z (for timestamps), and X (for hexadecimal literals). Here are more examples of typed literals:

Data Type

Typed Literal

Date

D’2008-03-15’

Time

T’08.56.20’

Timestamp

Z’2008-03-15-08.56.20.000000’

Hexadecimal

X’F0F0F0’


Defining Constants

A named constant assigns a name to a literal so that you can reference the literal by its name throughout your program. The named constant’s value never changes during processing. The Dcl-c (Declare Constant) instruction defines the named constant:

Programming in ILE RPG: Declaring Named Constants - Figure 3

The Dcl-c instruction requires only the name of the constant and its value. The constant is defined with no specific length or type; those attributes are implicit in the value. The data item name must begin with an alphabetic character or the special character $, #, or @. The remaining characters can be alphabetic characters, numbers, or any of the four special characters _, #, $, and @. A data item name cannot contain blanks embedded within the permissible characters.

You enter the literal value of the constant following the name. Enter numeric constant values with a radix character or sign if appropriate, but never with thousands separators. Enclose character constant values within apostrophes. Constants of other data types should follow the rules indicated earlier for typed literals. Here are some valid constants:

Programming in ILE RPG: Declaring Named Constants - Figure 4

You might occasionally see the value for a named constant coded within parentheses following the Const keyword. This notation is valid but optional, and most programmers prefer simply to code the value without the Const keyword. The following two constant declarations are equivalent:

Programming in ILE RPG: Declaring Named Constants Figure 5

A character constant can be at most 16,380 bytes, and a numeric constant can contain up to 63 digits, with up to 63 decimal positions. To enter a named constant too long to fit on a single line, continue the value onto the next line, using a plus sign (+) to signal that the constant resumes with the first nonblank character on the next line.

 

Tip

Always use a named constant instead of a literal in your program, unless the use of the literal is obvious. Using named constants makes your programs much easier to read, understand, and maintain than if you use literals. For example, it’s easier to immediately understand the use of the term Taxrate than the literal .0765. It’s also easier to change the program later if the rate changes.

One exception to this rule might be the use of the literals '1' and '0', which have generally accepted meanings of *On and *Off, respectively.

 

Using Figurative Constants

ILE RPG includes a special set of reserved words called figurative constants, which are implied literals that can be used without a specified length. Figurative constants assume the length and decimal positions of the variables with which they are associated. Some of RPG’s figurative constants are as follows:

  • *Blank (or *Blanks)
  • *Zero (or *Zeros)
  • *Off
  • *On
  • *Hival
  • *Loval
  • *All
  • *Null

RPG lets you assign *Blank or *Blanks to cause a character variable to be filled with blanks. Assigning *Zero or *Zeros to both numeric and character variables fills the variables with 0s.

Figurative constants *Off and *On represent '0' and '1' character values. *Off is the equivalent of '0', and *On equates to '1'. Although you can use *Off and *On with any character variable of any length, programmers most often use *Off and *On to either change or compare an indicator’s value.

Assigning *Hival fills a variable with the highest possible collating value appropriate to its data type. Setting a character variable to *Hival sets all the bytes to hexadecimal FF (all bits on). For a numeric variable, *Hival is the maximum positive value allowed for the data representation, usually all 9s and a plus sign (+). Assigning *Loval fills a variable with the lowest possible collating value appropriate to its data type—for example, hexadecimal 00 (all bits off) for character variables and the minimum negative value for numeric variables. Programmers often assign *Hival or *Loval to a variable to ensure that the variable’s value is the maximum or minimum possible.

Assigning figurative constant *All immediately followed by one or more characters within apostrophes repeats the string within the apostrophes cyclically through the entire length of the result variable. For example, assigning *All'Z' to a character variable fills the variable with Zs, and assigning *All'7' to a numeric variable fills the variable with 7s.

The constant *Null represents a null value. You generally use *Null to represent the absence of any value—which is not the same as using blanks or zeros. Usually, ILE RPG uses *Null only in unusual situations, which we examine later.

Next time: Defining Standalone Variables.  What to learn more now?  Buy Programming in ILE RPG, Fifth Edition at the MC Press Bookstore today!

James Buck
Jim Buck's career in IT has spanned more than 35 years, primarily in the college education, manufacturing, and healthcare industries. Past president (13 years) of the Wisconsin Midrange Computer Professional Association, he has served on several teams developing IBM and COMMON certification tests. Jim has co-authored several IBM i textbooks with Bryan Meyers that are used by many companies and in colleges worldwide. Other accomplishments include: recipient of the 2007 IBM System i Innovation - Education Excellence Award, 2014 COMMON President's Award, and 2013/2016/2017 IBM Champion - Power Systems.

Jim is the president and founder of imPower Technologies, where he provides professional IBM i training and consulting services. He is active in the IBM i community, working to help companies train their employees in the latest IBM technologies and develop the next generation of IBM i professionals.

MC Press books written by Jim Buck available now on the MC Press Bookstore.

Control Language Programming for IBM i Control Language Programming for IBM i
Master the A-Z of CL, including features such as structured programming, file processing enhancements, and ILE.
List Price $79.95

Now On Sale

Mastering IBM i Mastering IBM i
Get the must-have guide to the tools and concepts needed to work with today's IBM i.
List Price $85.95

Now On Sale

Programming in ILE RPG Programming in ILE RPG
Get the definitive guide to the RPG programming language.
List Price $95.95

Now On Sale

Programming in RPG IV Programming in RPG IV
Understand the essentials of business programming using RPG IV.
List Price $79.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: