Game Development Reference
In-Depth Information
Colors color = Colors::Red;
switch (color)
{
case Colors::Red:
{
cout << "The color is Red!";
}
break;
case Colors::Green:
{
cout << "The color is Green";
}
break;
default:
{
cout << "Unknown color!";
}
break;
}
return 0;
}
You can see from this example that the switch statement can be used to create blocks of code
(cases) that will execute for values that we are aware of at compile time. enums are perfect
candidates for this type of statement. Listing 6-9 did not include a case block for the Blue value. This
omission allowed us to look at the default case. The default case is supplied to provide a default
behavior to the switch so that we can properly handle situations that need either a default behavior
or to catch an error.
Listing 6-9 also sees the introduction of the break keyword. This new keyword allows us to break
out of a statement block. If we had missed this in our switch, the program would have created the
following output (assuming we add endl to each line):
The color is Red!
The color is Green!
Unknown color!
Missing the break in each block would cause the code to flow from one block to the next.
Sometimes this is the behavior we desire, but more often than not it is a bug.
Note This is our first mention of code bugs! Games are large projects and bugs can be caused by many
complicated interactions in code. This example of missing a single word is just one example of how bugs can
enter our code.
 
Search WWH ::




Custom Search