ABAP - Keyword Documentation →  ABAP - Reference →  Program Flow Logic →  Conditional Expressions → 

SWITCH - Conditional Operator


... SWITCH type( [let_exp]
                 WHEN const1 THEN [ let_exp] result1
               [ WHEN const2 THEN [ let_exp] result2 ]
               [ ELSE [ let_exp] resultn ] ) ...


A conditional expression with the conditional operator SWITCH has a result, result, that is specified by a case distinction. Either a value with the data type specified by type is produced or a class-based exception raised. The following can be specified for type:

All operands specified after THEN must be convertible to the data type determined by type. In the case of reference variables, an up cast must be possible.

The position operand in the parenthesis is the value checked in the case distinction. This is a general expression position. It must be followed by at least one WHEN. Literals and constants can be specified for const behind WHEN. It must be possible to compare them with operand. This can be followed by any number of WHENs with further constant values. An ELSE can be specified at the end. This expression compares the values of the operand operand with the specified constant values, one by one, and chooses the result behind THEN for which the values of operand and constant are identical for the first time. The selected result determines the result of the conditional expression. If no matches are found, the result specified after ELSE is selected. If ELSE is not specified, the result is the initial value of the data type type.

If an item specified after THEN or ELSE can be selected, either the result is set or a class-based exception is raised, just as with a conditional expression COND.

A LET expression can be specified in front of the operand operand, after every THEN. and after ELSE to define local auxiliary fields.


COND type( WHEN operand = const1 THEN result1
         [ WHEN operand = const2 THEN result2 ]
         [ ELSE resultn ] )

Rules apply when deriving the type in cases where # is specified for actual parameters that can be passed to generically typed formal parameters. These rules prevent syntax errors in programs that call a procedure and the procedure makes the full typing of a formal parameter type more general by switching to a generic type.


Conditional operator SWITCH in an operand position in a loop. The loop is exited when the exception after ELSE is caught.

CLASS cx_overflow DEFINITION INHERITING FROM cx_static_check.

DATA(out) = cl_demo_output=>new( ).
        SWITCH string( sy-index
                       WHEN 1 THEN 'one'
                       WHEN 2 THEN 'two'
                       WHEN 3 THEN 'three'
                       ELSE THROW cx_overflow( ) ) ).
    CATCH cx_overflow.
      out->display( ).