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 ...

Get C++ Quick Syntax Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.