The if Statement

When a C++ program must choose whether or not to take a particular action, you usually implement the choice with an if statement. The if comes in two forms: if and if else. Let's investigate the simple if first. It's modeled after ordinary English, as in “If you have a Captain Cookie card, you get a free cookie.” The if statement directs a program to execute a statement or statement block if a test condition is true and to skip that statement or block if the condition is false. Thus, an if statement lets a program decide whether a particular statement should be executed.

The syntax is similar to the while syntax:

if (test-condition)
    statement

A true test-condition causes the program to execute statement, which can be a single ...

Get C++ Primer Plus, Fourth Edition 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.