|
|
 |
 |
Chapter 4 Control Structures I
Control structures in C++ fall into two categories: selection and repetition. The focus of this chapter is on the two selection structures available to you in C++. In previous chapters, you have had to rely on well-formed data for your programs, and you could not take alternate logical paths with your program designs. With selection structures, you are able to make one or two-way decisions with an if statement, and you can move through multiple possible paths by using a switch statement. Your decisions are either based on the relationship between values, with the relational operators, or you may make decisions based on the value of a simple data variable. A simple comparison, such as deciding if a value is equal to another value, is one building block when creating “logical expressions”, since the relational operators return a value of the logical type bool. You can combine these operations with the logical operators.
An interesting and useful tip to remember when working with logical expressions is that any integral expression may be used in a logical expression due to the automatic type conversion that takes place in C++. Finally, you can use the multi-branching switch statement to perform statements based on the value under consideration in the switch. A switch statement is like a highway with many access points, and certain designated exit points. When you construct a switch statement, the value of the variable is compared to each label in the switch statement. Execution begins at the first matching label and continues until the end of the switch statement is reached or until an exit point, caused by the break statement, is encountered. Selection statements are powerful tools that allow you to make decisions and branches in your code.
|
|
|
 |