CHAPTER 9

image

Conditionals

Conditional statements are used to execute different code blocks based on different conditions.

If Statement

The if statement will only execute if the expression inside the parentheses is evaluated to true. In C++, this does not have to be a Boolean expression. It can be any expression that evaluates to a number, in which case zero is false and all other numbers are true.

if (x < 1) {
   cout << x << " < 1";
}

To test for other conditions, the if statement can be extended by any number of else if clauses.

else if (x > 1) {
   cout << x << " > 1";
}

The if statement can have one else clause at the end, which will execute if all previous conditions are false.

else {
   cout << x << " == 1";
}

As for the curly brackets, they can be left out if only a single statement needs to be executed conditionally. However, it is considered good practice to always include them since they improve readability.

if (x < 1)
   cout << x << " < 1";
else if (x > 1)
   cout << x << " > 1";
else
   cout << x << " == 1";

Switch Statement

The switch statement checks for equality between an integer and a series of case labels, and then passes execution to the matching case. It may contain any number of case clauses and it can end with a default label for handling all other cases.

switch (x)
{
    case 0: cout << x << " is 0"; break;
    case 1: cout << x << " is 1"; break;
    default: cout << x << " is not 1 or 2"; break;
}

Note that the statements after each case label end with the break keyword to skip the rest of the switch. If the break is left out, execution will fall through to the next case, which can be useful if several cases need to be evaluated in the same way.

Ternary Operator

In addition to the if and switch statements there is the ternary operator (?:) that can replace a single if/else clause. This operator takes three expressions. If the first one is true then the second expression is evaluated and returned, and if it is false, the third one is evaluated and returned.

x = (x < 0.5) ? 0 : 1; // ternary operator (?:)

C++ allows expressions to be used as stand-alone code statements. Because of this the ternary operator cannot just be used as an expression, but also as a statement.

(x < 0.5) ? x = 0 : x = 1; // alternative syntax

The programming term expression refers to code that evaluates to a value, whereas a statement is a code segment that ends with a semicolon or a closing curly bracket.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.78.83