The case(expression)
statement is used within a switch
function to specify distinct branches of code execution based on the value of an expression. This variant supports both numeric literals and string literals, expanding the flexibility of the traditional switch-case construct.
Structure of the case
Statement
Components:
- Expression: The value used in the switch to determine which
case
block to execute. - Case Blocks: Each
case(expression)
defines a value or condition that, when matched, triggers the execution of the associated code block. - String and Numeric Literals: The
case
statement supports matching against both numeric and string literals.
Simple Example
item = “apple”;
switch (item) {
case(“apple”):
lib.log(“Fruit is apple”);
case(“orange”):
lib.log(“Fruit is orange”);
case(1):
lib.log(“Fruit is identified by number 1”);
default:
lib.log(“Unknown fruit”);
}
- Matching Strings: The switch-case structure now accommodates strings, allowing
case("apple")
to match descriptive values. - Numeric Handling: Numeric literals like
case(1)
provide compatibility with traditional integer cases. - Default Handling: Ensures that there’s a fallback procedure if none of the cases match the expression value.
Practical Use
- Flexible Branching: Supports more intuitive branching logic by allowing complex and descriptive conditions, enhancing code clarity.
- String Matching: Ideal for scenarios where the input is not limited to numbers, such as command parsing or user interactions.
- Improved Readability: Using more descriptive expressions can lead to more readable and maintainable code, capturing intent clearly.
Considerations
- No Fallthrough: As designed, typically with automatic fallthrough prevention, this approach eliminates the need for
break
statements within each case block. - Default Case: While the default clause is optional, providing it when possible improves robustness against unexpected expression values.
The case(expression)
statement improves upon traditional usage by improving flexibility and documentation appearance, supporting wider application use cases across varied input types in switch-controlled structures.