C++ Tutorial – 11 – 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.
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 (code that returns a value) to be used as stand-alone code statements. This behavior is different to, for example, Java or C#. Because of this the ternary operator can also be used as a statement. For example, the expressions themselves can contain the assignments, in which case the assigned value will be the one that is returned.
(x < 0.5) ? x = 0 : x = 1; // alternative syntax
If you like this tutorial please +1 it:


![[Affiliate link] Total Training]( http://d3qzmfcxsyv953.cloudfront.net/images/pvt-affiliates/totaltraining.png)
![[Affiliate link] Lynda](http://d3qzmfcxsyv953.cloudfront.net/images/pvt-affiliates/lynda.png)

