Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Control flow
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Case and switch statements === {{Main article|Switch statement}} [[Switch statement]]s (or ''case statements'', or ''multiway branches'') compare a given value with specified constants and take action according to the first constant to match. There is usually a provision for a default action ("else", "otherwise") to be taken if no match succeeds. Switch statements can allow compiler optimizations, such as [[lookup table]]s. In [[dynamic language]]s, the cases may not be limited to constant expressions, and might extend to [[pattern matching]], as in the [[shell script]] example on the right, where the <code>*)</code> implements the default case as a [[glob (programming)|glob]] matching any string. Case logic can also be implemented in functional form, as in [[SQL]]'s <code>decode</code> statement.<!--Perl's implementation of case as a lookup table--> {| class="wikitable" |- ! [[Pascal (programming language)|Pascal]]: ! [[Ada (programming language)|Ada]]: |- |<syntaxhighlight lang="pascal"> case someChar of 'a': actionOnA; 'x': actionOnX; 'y','z':actionOnYandZ; else actionOnNoMatch; end; </syntaxhighlight> |<syntaxhighlight lang="ada"> case someChar is when 'a' => actionOnA; when 'x' => actionOnX; when 'y' | 'z' => actionOnYandZ; when others => actionOnNoMatch; end; </syntaxhighlight> |- ! [[C (programming language)|C]]: ! [[Shell script]]: |- |<syntaxhighlight lang="c"> switch (someChar) { case 'a': actionOnA; break; case 'x': actionOnX; break; case 'y': case 'z': actionOnYandZ; break; default: actionOnNoMatch; } </syntaxhighlight> |<syntaxhighlight lang="bash"> case $someChar in a) actionOnA ;; x) actionOnX ;; [yz]) actionOnYandZ ;; *) actionOnNoMatch ;; esac </syntaxhighlight> |- ! [[Lisp (programming language)|Lisp]]: ! [[Fortran]]: |- | <syntaxhighlight lang="lisp"> (case some-char ((#\a) action-on-a) ((#\x) action-on-x) ((#\y #\z) action-on-y-and-z) (else action-on-no-match)) </syntaxhighlight> | <syntaxhighlight lang="fortran"> select case (someChar) case ('a') actionOnA case ('x') actionOnX case ('y','z') actionOnYandZ case default actionOnNoMatch end select </syntaxhighlight> |}
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)