1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Tutorial - Lesson Five - About Control Statements

By David Bolton, About.com

5 of 5

About Switch Statements

When there are many choices, a switch statement may be better than an if. The syntax of a switch statement is:
switch ( expression) {

case a: statement1; break;
case b: statement2;
case d: statement3; break;
default: statement4;

}
Notes: Expression should be an int or a char type. e.g.
switch (character) {

case 'B':
case 'b': statement1; break;
case 'c': statement2;
case 'd': statement3; break;
default: statement4;
}
If the character is 'B' or 'b' then statement1 is executed, but if the character is 'c' then statement2 and statement3 are both executed. With 'd' though, only statement3 is executed. For all other characters statement4 is executed.

When a case matches, all statements from that case on, including those that follow are executed until a break is found. This is known as 'Fall Through'.

switch (value) {
case 3:statement3;
case 2:statement2;
case 1:statement1;
default: break;
}
In this example, I've exploited 'fall through' so that for any number 1-5, statements n; n-1 down to 1 are executed. Eg if value ==3, statement3, statement2 and statement1 are executed (in that order).

Notes about Switch

  • Each case can have one or more statements without needing to be enclosed by curly brackets.
  • The default case can occur anywhere.
  • Good Practice to use default, perhaps to trap errors.
That completes this lesson on control statements. Learn about functions in the next lesson.

Index: C Tutorial - Lesson Five - About Control Statements

  1. Control Statements
  2. The For Loop
  3. Break and Continue
  4. While and Do While
  5. About Switch Statements

5 of 5

Explore C / C++ / C#

More from About.com

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. About Switch Statements

©2008 About.com, a part of The New York Times Company.

All rights reserved.