C++ Decision Making
A decision structure requires the programmer to specify one or more conditions to be evaluated or tested, along with a statement (required) to execute if the condition is true and an optional statement to execute if the condition is false.
The following is the general form of a typical decision structure in most programming languages:
Decision Statements
The C++ programming language provides the following types of decision statements. Click the links to see the details of each statement.
| Statement | Description |
|---|---|
| if statement | A if statement if statement consists of a Boolean expression followed by one or more statements. |
| if...else statement | A if statement An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. |
| Nested if statements | You can use one if or else if if statement inside another if or else if if statement. |
| switch statement | A switch A switch statement allows testing a variable against multiple values. |
| Nested switch statements | You can use one switch You can use another **switch** statement inside a switch statement. |
? : Operator
We have explained the conditional operator ? :in a previous chapter, which can be used to replace if...else an if...else statement. Its general form is as follows:
Exp1 ? Exp2 : Exp3;
Here, Exp1, Exp2, and Exp3 are expressions. Note the use and position of the colon.
The value of the ? expression is determined by Exp1. If Exp1 is true, Exp2 is evaluated and the result is the value of the entire ? expression. If Exp1 is false, Exp3 is evaluated and the result is the value of the entire ? expression.