Show TOC

ConstantsLocate this document in the navigation structure

Constants are named data objects that you create statically using a declarative statement. They allow you to store data under a particular name within the memory area of a program. The value of a constant must be defined when you declare it. It cannot subsequently be changed. The value of a constant cannot be changed during the execution of the program. If you try to change the value of a constant, a syntax error or runtime error occurs.

You declare constants using the CONSTANTS statement. Within the program, you can also declare local variables within procedures using CONSTANTS. The same rules of visibility apply to constants as apply to the visibility of data types. Local constants in procedures obscure identically-named variables in the main program. Constants exist for as long as the context in which they are declared.

The syntax of the CONSTANTS statement is exactly the same as that of the DATA statement, but with the following exceptions:

  • You must use the VALUE addition in the CONSTANTS statement. The start value specified in the VALUE addition cannot be changed during the execution of the program.
  • You cannot define constants for XSTRINGS, references, internal tables, or structures containing internal tables.
    Tip

    Elementary constants:

    CONSTANTS: pi     TYPE p DECIMALS 10 VALUE '3.1415926536'.

    ref_c1 TYPE REF TO C1 VALUE IS INITIAL.

    The last line shows how you can use the IS INITIAL argument in the VALUEaddition. Since you must use the VALUE addition in the CONSTANTS statement, this is the only way to assign an initial value to a constant when you declare it.

    Complex constants:

    CONSTANTS: BEGIN OF myaddress,           name     TYPE c LENGTH 20 VALUE 'Fred Flintstone',           street   TYPE c LENGTH 20 VALUE 'Cave Avenue',           number   TYPE p           VALUE  11,           postcode TYPE n LENGTH 5  VALUE  98765,           city     TYPE c LENGTH 20 VALUE  'Bedrock',           END OF myaddress.

    This declares a constant structure myaddress. The components can be addressed by myaddress-name, myaddress-street, and so on, but they cannot be changed.