Concept Flow - Switch statement
Start
Evaluate expression
Match case?
No→Default case if exists
Yes
Execute matched case
End
The switch statement evaluates an expression, matches it to a case, executes that case, or the default if no match.
x <- "b" switch(x, a = "Apple", b = "Banana", c = "Cherry", "Unknown fruit")
| Step | Expression Value | Case Checked | Match? | Action | Output |
|---|---|---|---|---|---|
| 1 | "b" | a | No | Check next case | |
| 2 | "b" | b | Yes | Return "Banana" | Banana |
| 3 | N/A | Stop | N/A | Exit switch | Banana |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| x | "b" | "b" | "b" | "b" |
switch(expression, case1 = value1, case2 = value2, ..., default) - Evaluates expression once - Matches expression to cases by name or position - Executes first matching case - Returns default if no match - Stops after first match