switch Integer multiway selection statement
switch Integer multiway selection statement
switch selects a case by integer value, or default. Fall-through can share code or surprise; break or return exits. No floating-point or string controls.
| Category | Control flow |
|---|---|
| Kind | Keyword / Statement |
| C standard | C89 / C90 |
📝 Syntax
switch (n) { case 1: ...; break; default: ...; }
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
one
one or two
🏷️ Related control-flow keywords
📚 Related Tutorials
❓ FAQ
QCan switch test strings or floating-point values directly?
ANo. Its control expression must have integer or enumeration type; string pointers and floating-point values are invalid. String dispatch normally uses an if chain with comparisons such as strcmp.
QMust every case in a switch include break?
ANo. break is only one way to leave a switch; return can leave the function, and consecutive labels or intentional fall-through can share code. Choose the control flow deliberately and document it clearly.
QCan an ordinary variable be used as the value after case?
ANo. A case label requires an integer constant expression. An ordinary variable does not qualify even if it is never changed after initialization. Use if statements or another lookup structure for runtime dispatch.