Core C++

Lesson 27 : Switch Statements

This C++ tutorial covers switch statements, an alternative to if statements for branching. Strictly speaking, anything that can be done with switch statement can also be done with an if. However, a switch is faster to execute and can often be more elegant.

Example 1:

The enumeration above defines videogame genres: turn-based strategy, first-person shooter, role-playing game, and real-time strategy. Below, we define a function with a switch statement to print out the genre that is passed in. The switch contains a branch for each genre, represented by a constant integer.

A switch only allows us to compare a variable to a set of constant values and branch based on equality; so it is more restricted than an if. In this example, we have four branches, which simply print the genre. For each branch, the case statement defines the beginning of the branch and the break statement defines the end.

Here, we create genres types for five videogames: World of Warcraft, Age of Empires III, Civilization IV, Dungeon Siege II, and Halo III. The assigned genres are define for each game and we call the PrintGenre() function for each. Executing the program, we se that program prints the expected genre for each game. Of course, this example is only for illustration: for most programs, we would define more complex branches, which would do more than simply print a message.

Example 2:

In this second example, we define an enumeration of book types: Mystery, Novel, Fiction, and Non-fiction. For our purposes, we will consider all mystery books to be novels and all novels to be fiction. We can represent this relationship in a switch statement like this:

This function, which prints the book type, uses a set of nested case statements to print mystery, novel, and fiction if the book type is a mystery. Notice that we do not hit a break statement until we get into the fiction case statement. A break is always required to exit the switch statement before the end. Notice also, that we have defined a default branch. The default branch is executed when no other case executed.

In the main function above, we create book types for three books: Ayn Rand's Atlas Shrugged, C.S. Lewis' The Lion, the Witch, and the Wardrobe, and Plato's The Republic. Then, we call the PrintBookType() function for each of these types and the number 85, which we convert to a book type. To clarify the execution, we print a line space between each call. So, we see that Atlas Shrugged is a mystery, a novel and fiction, for example. Also, the 85 that we converted is not represent in our cases. So, that function call executes the default branch and prints "Unknown Type."

 

© 2007–2024 XoaX.net LLC. All rights reserved.