CASE Statements
The CASE
statement is used when a variable or expression can have multiple discrete values and you want to execute different logic depending on each value. It's similar to switch statements in other languages.
Syntax
CASE <expression> OF
<value1>: <statements>;
<value2>: <statements>;
...
ELSE
<default_statements>;
END_CASE;
<expression>
must be a value like anDINT
- Each
<value>
represents a possible match ELSE
is optional but recommended as a fallback- Always end with
END_CASE;
Example: Mode Selector
CASE Mode OF
1: Operation := 'Auto';
2: Operation := 'Manual';
3: Operation := 'Maintenance';
ELSE
Operation := 'Unknown';
END_CASE;
Example: Speed Level Control
CASE Speed_Level OF
0: Motor_Speed := 0;
1: Motor_Speed := 25;
2: Motor_Speed := 50;
3: Motor_Speed := 100;
ELSE
Motor_Speed := 0; // Default if out of range
END_CASE;
When to Use CASE Instead of IF
Use CASE
when:
-
You’re checking one variable against multiple values
-
You want better readability than multiple
IF...ELSIF
blocks -
Your logic branches are simple and based on a single input
Notes
-
CASE
only checks for equality (=
). It does not support relational operators (<
,>
, etc.) -
For range checks or more complex logic, use
IF...THEN...ELSE