3 Selection and Control Structures
A practical guide to using C++ conditions, branching statements, and value-selection expressions safely and clearly.
Foundations: Boolean Conditions
A selection structure lets a C++ program choose which statements to execute. The decision begins with a condition, and the result determines which branch runs.
A produces true or false. C++ also contextually converts an expression to bool: zero behaves as false, and a nonzero value behaves as true. Although if (count) is valid when count is an integer, if (count > 0) usually states the intention more clearly.
create conditions by comparing values. For example, score >= 60 tests whether a score reaches the passing threshold. can combine tests: age >= 18 && hasId requires both conditions, while isAdmin || isOwner requires at least one.
The key takeaway is to make each condition express the decision clearly, especially when numeric values are being converted to Boolean results.
Branching with if and else
The main branching tool for general conditions is the if statement. It executes its block only when the condition is true. Adding else provides a block for the false case, and only one of the two branches executes.
For several alternatives, use an . For example, a grading decision can test score >= 90, then score >= 80, then lower thresholds. The first true condition determines the result, so order matters: a score of 95 must encounter the 90 test before a broader lower threshold.
A nested conditional is useful when one decision depends on another, such as checking membership before checking age. If the logic is simple, combining the tests with && may be clearer than nesting. Always use braces to show exactly which statements belong to each branch.
The key takeaway is that if handles general logic, while ordered else if branches handle mutually exclusive alternatives.
Clarity and Common Conditional Errors
Nested conditionals can become confusing when braces are omitted. In the situation, an else attaches to the nearest preceding unmatched if, not necessarily to the outer condition that a reader expects.
For example, in a nested, brace-free structure, the else after the inner statement belongs to the inner if. Adding braces removes the ambiguity and documents the intended structure. Braces also prevent a common error in which only the immediately following statement is controlled by an if, while a later statement executes unconditionally.
When writing conditions, remember that assignment and equality testing are different operations. if (x = 0) assigns a value, whereas if (x == 0) tests whether the value is zero. For floating-point values, direct equality can be unreliable; when appropriate, compare the difference against a small tolerance using an absolute-value function.
The key takeaway is to use braces, distinguish = from ==, and make numerical comparisons appropriate to the data type.
Fixed Choices with switch
A is useful when one integral or enumeration expression is compared with several fixed constant values. The program evaluates the expression, transfers control to the matching case, and uses default when no case matches and a default branch is present.
A break normally exits the switch. Without it, execution continues into the following case, producing . can be intentional when multiple values share an action, such as both lowercase and uppercase versions of a command. Otherwise, include break to prevent unintended execution of later cases.
A switch is not designed for range conditions such as score >= 90; use an if and for those decisions. Because control can jump directly to a case label, put declarations that require initialization inside braces so each case has its own local scope.
The key takeaway is to choose switch for fixed-value choices, document intentional , and use braces around case-local declarations.
Choosing the Right Selection Structure
The is a compact way to select one of two values in an expression. Its form is condition ? value_if_true : value_if_false. For example, an age can select the string adult or minor in a single assignment.
Only the selected alternative is evaluated. This makes the operator useful for short value choices in assignments, output, or return expressions. It is less suitable when either branch performs several statements or when multiple nested conditions would make the expression difficult to read.
Choose a structure according to the decision:
Use
iffor one condition, ranges, or complex logic.Use
ifwithelse ifandelsefor ordered alternatives.Use nested
ifstatements when one decision depends on another, unless combining conditions is clearer.Use
switchfor one integral or enumeration expression matched against fixed values.Use the for a short choice between two values.
The key takeaway is that concise syntax is useful only when it preserves clarity.