Summary -
In this topic, we described about the below sections -
Static variable initialized only once when the program or function or include etc, execution started and doesn't initialize until the end of the program or function or include etc,. The value assigned to the static variable retain until the end of the program or function or include etc, execution.
Static variable is a global variable. Static variables are declared in subroutines, function modules and static methods. Static variable life time is linked to the context of declaration.
The "DATA" statement used to declare variables whose lifetime is linked to the context of the declaration.
The "STATICS" statement used to declare variables with static validity in procedures.
The "CLASS-DATA" statement used to declare static variables within classes.
The "PARAMETERS" statement used to declare elementary data objects that are linked to an input field on a selection screen.
The "SELECT-OPTIONS" used to declare an internal table that is linked to input fields on a selection screen.
Guidelines for variable declaration -
- Hyphens should be avoided in variable declaration.
- Any ABAP keyword or clause name should not be used.
- User can't use special characters like 't', ','.
Example -
Write a simple program to get clear understanding of static variable.
Code -
*&---------------------------------------------------------------------*
*& Report Z_STATIC
*&---------------------------------------------------------------------*
*& Program Written by TUTORIALSCAMPUS
*&---------------------------------------------------------------------*
REPORT Z_STATIC.
* Loop for 5 times.
DO 5 TIMES.
* Perform addition Subroutine.
PERFORM addition.
ENDDO.
* Subroutine addition declaration and coding.
FORM addition.
* Initializing static variable.
STATICS lv_static TYPE I VALUE 99.
* Adding 1 to static variable.
lv_static = lv_static + 1.
* Display static variable.
WRITE: / lv_static.
ENDFORM.
Output -
Explaining Example -
In the above example, each and every statement is preceeded with a comment to explain about the statement. Go through them to get clear picture of example code.
Coming to output, lv_static variable is declared in the subroutine and it is static to the addition subroutine. So the lv_static variable got initialized only when the first time addition subroutine called. During the first sobroutine call, the lv_static variable initialized with 99, adds 1 to 99 and result 100 is displayed for the first time. For the second time subroutine call, the value 100 from the first call retains in lv_static variable, adds 1 to 100 and result 101 displayed in second iteration.
In the above example, we have called addition subroutine 5 times. So, the lv_static variable value incementing by 1 every time and display output 100, 101, 102, 103 and 104.