Conditional Statements in C++
The If Statement
- Basic structure involves checking a condition and executing code based on whether the condition is true or false.
Multiple Alternatives
- Multiple
if statements can be combined to evaluate complex decisions. - Use multiple
if statements to implement multiple alternatives. - Order matters: Pay attention to the order of conditions in multiple
if statements.
Example: Richter Scale
- Multiple branches for different descriptions of damage based on the Richter scale value.
- Code example:
if (richter >= 8.0) {
cout << "Most structures fall";
} else if (richter >= 7.0) {
cout << "Many buildings destroyed";
} else if (richter >= 6.0) {
cout << "Many buildings considerably damaged, some collapse";
} else if (richter >= 4.5) {
cout << "Damage to poorly constructed buildings";
} else {
cout << "No destruction of buildings";
}
- If a test is false, that block is skipped, and the next test is made.
- As soon as one test succeeds, its block is executed, and no further tests are attempted.
The Switch Statement
- Used for a sequence of
if statements that compares a single value against several constant alternatives. - Can only be used with integer or character types.
- Example:
int digit;
switch (digit) {
case 1: digit_name = "one"; break;
case 2: digit_name = "two"; break;
case 3: digit_name = "three"; break;
case 4: digit_name = "four"; break;
case 5: digit_name = "five"; break;
case 6: digit_name = "six"; break;
case 7: digit_name = "seven"; break;
case 8: digit_name = "eight"; break;
case 9: digit_name = "nine"; break;
default: digit_name = ""; break;
}
- The
default branch is chosen if none of the cases matches. - Every branch of the
switch must be terminated by a break statement. - If the
break is missing, execution falls through to the next branch.
Common Error
- Forgotten
break in switch statement can lead to unintended fall-through. - Many programmers consider the
switch statement somewhat dangerous and prefer the if statement.