SAPHub

ABAP Subroutine

Subroutines are procedures that we define in an ABAP program and can be called from any program. Subroutines are normally called internally, i.e. called from the same program in which it is defined. But it is also possible to call a subroutine from an external program. Subroutines cannot be nested and are usually defined at the end of the program.

A subroutine can be defined using FORM and ENDFORM statements.

FORM <subroutine name>.
 ...

ENDFORM.

A subroutine can be called using PERFORM statement.

PERFORM <subroutine name>.

Example Program.

PERFORM sub_display.
WRITE:/ 'After Perform'.

*&---------------------------------------------------------------------*
*&      Form  sub_display
*&---------------------------------------------------------------------*
FORM sub_display.
  WRITE:/ 'Inside Subroutine'.
ENDFORM.                    " sub_display

Output

Subroutines can call other subroutines and may also call themselves. Once a subroutine has finished running, the control returns to the next statement after the PERFORM statement.

We can terminate a subroutine by using the EXIT or CHECK statement.

EXIT statement can be used to terminate a subroutine unconditionally. The control returns to the next statement after the PERFORM statement.

PERFORM sub_display.
WRITE:/ 'After Perform Statement'.

*&---------------------------------------------------------------------*
*&      Form  sub_display
*&---------------------------------------------------------------------*
FORM sub_display.
  WRITE:/ 'Before Exit Statement'.
  EXIT.
  WRITE:/ 'After Exit Statement'.  " This will not be executed
ENDFORM.                    " sub_display

Output

CHECK statement can be used to terminate a subroutine conditionally. If the logical expression in the CHECK statement is untrue, the subroutine is terminated, and the control returns to the next statement after the PERFORM statement.

DATA: flag TYPE c.
DO 2 TIMES.
  PERFORM sub_display.
ENDDO.
WRITE:/ 'After Perform Statement'.

*&---------------------------------------------------------------------*
*&      Form  sub_display
*&---------------------------------------------------------------------*
FORM sub_display.
  WRITE:/ 'Before Check Statement'.

  CHECK flag NE 'X'.
  WRITE:/ 'Check Passed'.
  flag = 'X'.
ENDFORM.                    " sub_display

Output