Falling through switch statements


Home

About the Author

General Programming

Pascal

Delphi

C&C++

Visual Basic

SQL

JAVA Script

Links

 

Assert vs Verify ] Constructors and Destructors ] [ Falling through switch statements ] Memory Leaks ] Null Terminator ] Rogue array pointers ]

The problem: When a switch statement evaluates its cases and one of its cases are found to be true, then of all the remaining events listed in the rest of the switch block will execute unless a break is found.

Here's an example:

int Number = 1;

switch (Number)

{

case 0:

cout << "Number is zero";

case 1:

cout << "Number is one";

case 2:

cout << "Number is two";

}

Logically, since Number is 1, then the output would be Number is one; However, Number is oneNumber is two is the output. Without the break keyword, the remaining events fall through and execute until either a break is found later on or the switch block ends.

The solution: Here is the correct switch block:

switch (Number)

{

case 0:

cout << "Number is zero" <<endl;

break;

case 1:

cout << "Number is one" <<endl;

break;

case 2:

cout << "Number is two" <<endl;

break;

}

Now it will behave the way the you expected it to. Those coming from Visual Basic will note that this isn't necessary in a select case (VB's equivalent to a switch case), and this could be an understandable pitfall. Sometimes (although rarely) you may wish for your case events to fall through--which in that instance you would pull out the breaks. However, most of the time you wouldn't, and you defineately want to watch out for this.

Link of the week 
http://www.cpp-
programming.
com/
Newsgroups
comp.lang.c
comp.lang.c++
comp.programming

This page is best viewed in 800x600x256. This page was last edited Saturday, July 15, 2000

1