Control Flow

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

A program is a list of statements, and by default they run one after the other from the top. Control flow is what lets a program break out of that straight line: it can run a block of statements only when a condition is true, pick one of several blocks, repeat a block several times, or stop early. This page explains these tools in plain terms, starting with decisions (IF and CASE), then repetition (DO and WHILE) and then the statements that jump out of a block (CHECK, EXIT, CONTINUE and RETURN). It is written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608). All of these statements work the same way in ABAP Cloud and in classic, Standard ABAP only, code on premise; a short section at the end lists older habits you will meet in classic programs. After reading it you can route a claim by its amount, repeat a step safely and leave a loop or a method at the right moment. The example is the approval routing of the Expense claims running example (ZEXP_CLAIM).

Before you read

Key terms

  • Logical expression: a condition built from comparisons and the words AND, OR and NOT, which is either true or false.

  • Branch: one of the alternative blocks of statements of which only one is run, chosen by a condition.

  • Loop: a block of statements that is run again and again until a condition or a statement ends it.

  • sy-index: the system field that holds the number of the current pass through a DO or WHILE loop, starting at 1.

  • Processing block: a unit of code that the runtime enters and leaves as a whole, such as a method.

  • Runtime type: the actual class of an object at the moment the program runs, which can be more specific than the type of the variable that points to it.

Choosing with IF

IF runs a block only when its condition is true. ELSEIF adds another condition that is tested only if all earlier ones were false, and ELSE is the block that runs when none was true. The whole structure ends with ENDIF. The conditions are the logical expressions of the previous page: comparisons joined with AND, OR and NOT, with parentheses to group them. The first true branch wins and the rest are skipped, so the order of the branches matters: put the narrowest condition first.

The routing rules of the running example are: a claim of up to 100 is approved automatically, up to 1000 goes to the manager, and anything larger goes to the finance department. The listing is generic. It runs in the local playground when the class is written as a local class in a report: for the amounts 0, 50, 500 and 5000 it returns rejected, auto, manager and finance.

CLASS zcl_routing_demo DEFINITION PUBLIC FINAL CREATE PUBLIC.
  PUBLIC SECTION.
    CLASS-METHODS route_by_amount
      IMPORTING amount       TYPE decfloat34
      RETURNING VALUE(route) TYPE string.
ENDCLASS.

CLASS zcl_routing_demo IMPLEMENTATION.
  METHOD route_by_amount.
    IF amount <= 0.
      route = `rejected`.
    ELSEIF amount <= 100.
      route = `auto`.
    ELSEIF amount <= 1000.
      route = `manager`.
    ELSE.
      route = `finance`.
    ENDIF.
  ENDMETHOD.
ENDCLASS.

The same decision can be written as an expression instead of a statement, using COND (and SWITCH for a plain value-to-value mapping). An expression gives back a value, so it fits on the right of an assignment; a statement is better when each branch does several things. Both are covered in the page on constructor expressions. This listing runs in the local playground; for the amounts 500 and 5000 it gives manager and finance.

DATA amount TYPE decfloat34 VALUE 500.
DATA(route) = COND string( WHEN amount <= 100  THEN `auto`
                           WHEN amount <= 1000 THEN `manager`
                           ELSE `finance` ).

Choosing with CASE

When the same variable is compared with several fixed values, CASE is clearer than a chain of ELSEIF. The variable is named once after CASE, each WHEN lists one or more values separated by OR, and WHEN OTHERS takes everything that no WHEN matched. Unlike some other languages, only the matching WHEN block runs: there is no fall-through to the next one, and no break is needed.

CASE compares for equality only. For ranges, like the amount limits above, use IF.

The status of a claim is a good fit. The listing requires an SAP system; not run here, because it reads the table ZEXP_CLAIM.

SELECT SINGLE status FROM zexp_claim
  WHERE claim_id = @claim_id
  INTO @DATA(status).

CASE status.
  WHEN 'N' OR 'S'.
    text = `Waiting for approval`.
  WHEN 'A'.
    text = `Approved`.
  WHEN 'R'.
    text = `Rejected`.
  WHEN OTHERS.
    text = `Unknown status`.
ENDCASE.

CASE TYPE OF

A variable that points to an object can hold an object of the declared class or of any subclass. CASE TYPE OF tests that runtime type instead of a value. Each WHEN TYPE names a class or interface, and INTO can place the object in a new variable that already has the narrower type, so its extra methods can be called without a separate cast. WHEN OTHERS handles the rest. The WHEN blocks are tested from top to bottom, so name a subclass before its parent class. The listing requires an SAP system; not run here, because the classes are examples that are not part of the lab.

CASE TYPE OF document.
  WHEN TYPE zcl_exp_receipt INTO DATA(receipt).
    description = |Receipt { receipt->get_number( ) }|.
  WHEN TYPE zcl_exp_invoice INTO DATA(invoice).
    description = |Invoice { invoice->get_number( ) }|.
  WHEN OTHERS.
    description = `Other document`.
ENDCASE.

Repeating with DO and WHILE

A loop runs a block again and again. ABAP has two general-purpose loops, and a third for internal tables that is taught later.

  • DO ... ENDDO repeats a block. DO 5 TIMES. repeats it five times. Plain DO. repeats it without end, so the block must contain an EXIT or a RETURN, otherwise the program never finishes.

  • WHILE condition. ... ENDWHILE. tests the condition before every pass and stops when it is false. If the condition is false at the start, the block does not run at all.

  • LOOP AT ... ENDLOOP visits every row of an internal table and is taught in the page on internal tables.

Inside DO and WHILE, the system field sy-index holds the number of the current pass, counting from 1. In nested loops it refers to the loop that is currently running, so copy it to a variable first if an inner loop needs the outer number.

The listing sums the numbers 1 to 5 with DO, then halves an amount with WHILE until it is below 1. It runs in the local playground, where total ends as 15 and halvings as 5.

DATA total TYPE i.
DO 5 TIMES.
  total = total + sy-index.
ENDDO.

DATA amount TYPE decfloat34 VALUE 20.
DATA halvings TYPE i.
WHILE amount >= 1.
  amount = amount / 2.
  halvings = halvings + 1.
ENDWHILE.

Leaving and skipping: CHECK, EXIT, CONTINUE and RETURN

Four statements change the normal path through a block. Their effect depends on whether they stand inside a loop.

  • CONTINUE ends the current pass of the loop and starts the next one. It is valid only inside a loop.

  • EXIT inside a loop leaves the loop and runs the statement after its closing ENDDO, ENDWHILE or ENDLOOP. It acts on the loop it is written in.

  • CHECK condition is a short form of a negative test. Inside a loop, a false condition acts like CONTINUE. Outside a loop, a false condition leaves the current processing block, which in a method means leaving the method. The keyword documentation recommends CHECK and EXIT for loops only.

  • RETURN leaves the current method at once, from any depth of loops and branches. In a method with a returning parameter, the value is whatever has been assigned to that parameter so far.

The table sums this up.

Statement Inside a loop In a method, outside a loop

CONTINUE

Starts the next pass

Not allowed

EXIT

Leaves the innermost loop

Leaves the current processing block

CHECK cond

Starts the next pass when cond is false

Leaves the processing block when cond is false

RETURN

Leaves the whole method

Leaves the method

The flow of the approval routing of this page, ending in one of four routes, looks like this.

flowchart TD A["Claim with amount"] --> B{"Amount at most 0?"} B -- yes --> R["rejected"] B -- no --> C{"Amount at most 100?"} C -- yes --> AU["auto"] C -- no --> D{"Amount at most 1000?"} D -- yes --> M["manager"] D -- no --> F["finance"]

The listing shows the statements together. It goes through a list of amounts, skips empty ones, stops at the first amount that needs finance, and counts how many were routed automatically. It runs in the local playground with the result stated below.

DATA amounts TYPE STANDARD TABLE OF decfloat34 WITH EMPTY KEY.
amounts = VALUE #( ( 50 ) ( 0 ) ( 400 ) ( 2500 ) ( 80 ) ).

DATA auto_count TYPE i.
DATA stopped_at TYPE i.
LOOP AT amounts INTO DATA(amount).
  CHECK amount > 0.
  IF amount > 1000.
    stopped_at = sy-tabix.
    EXIT.
  ENDIF.
  IF amount > 100.
    CONTINUE.
  ENDIF.
  auto_count = auto_count + 1.
ENDLOOP.

In this run auto_count is 1 (only the amount 50; the 80 is never reached because of the EXIT), and stopped_at is 4.

A method that checks its inputs first usually uses RETURN or CHECK at the top to leave early. This keeps the main logic at one level of indentation instead of burying it in nested IF blocks. The listing requires an SAP system; not run here, because it works on the table ZEXP_CLAIM.

METHOD submit.
  IF claim_id IS INITIAL.
    RETURN.
  ENDIF.

  SELECT SINGLE * FROM zexp_claim
    WHERE claim_id = @claim_id
    INTO @DATA(claim).
  CHECK sy-subrc = 0.

  " ... route the claim here
ENDMETHOD.

Older material you may meet

Classic programs, and books written before ABAP 7.40, show older habits that still work in Standard ABAP.

  • CHECK and EXIT outside a loop leave the current processing block, and you may meet them in classic programs. The keyword documentation recommends them for loops only, so in new code use RETURN to leave a method.

  • Long ELSEIF chains that compare one variable with fixed values are older style; modern code uses CASE, or COND and SWITCH when only a value is needed.

  • Results are often tested with sy-subrc right after a statement, as in the last listing. This is still the normal way for SELECT SINGLE and many other statements.

  • Older programs declare every variable at the top. Today a variable is usually declared where it is first filled, with an inline declaration such as DATA(status).

Summary

  • IF, ELSEIF and ELSE run the first block whose condition is true; put the narrowest condition first.

  • CASE compares one variable with fixed values and runs only the matching WHEN block; WHEN OTHERS is the default.

  • CASE TYPE OF chooses by the runtime type of an object and can place it in a variable of the narrower type.

  • DO repeats a fixed number of times or until an EXIT, and WHILE repeats while its condition is true; sy-index counts the passes from 1.

  • CONTINUE skips to the next pass, EXIT leaves the innermost loop, CHECK skips or leaves when its condition is false, and RETURN leaves the method.

  • COND and SWITCH express a choice as a value; use statements when each branch does several things.