Skip to main content

Section 7.3 The if Statement

Now that we have boolean values, we need to use them to control what code gets executed. Conditional statements give us this ability. The simplest conditional statement in C++ is the if statement:
An if statement consists of if, followed by an expression in parentheses, followed by a block of code. The expression is used to determine whether the block of code should be executed.
if (x > 0) {
    cout << "x is positive" << endl;
    cout << "that means larger than 0";
}

Subsection 7.3.1 The condition

The expression in parentheses is called the condition and must be a variable or expression with a boolean value. If it is true, the statements in the curly braces get executed. That group of statements in the braces is known as the body. If the condition is false, execution skips over the body.
Flowchart showing the structure of an if statement.
Figure 7.3.1. Flow of execution for an if statement.
Try running this sample in Codelens. Notice that only one of the three conditions is true and that the bodies of the other two conditionals get skipped.
Listing 7.3.2.
The condition can be any value that evaluates to true or false. Because numbers can evaluate as true or false (with 0 being false and all other numbers being true), that means it is possible, but generally not advisable, to write something like this:
int x = 5;
if (x) {
    cout << "x is truish" << endl;
}
It also means that it is legal to use a variable of type bool without a comparison, as it already has a value of true or false:
Listing 7.3.3.
int x = 5;
bool isEven = (x % 2 == 0);
if (isEven) {
    cout << "x is even" << endl;
}
This way of testing a boolean variable is generally preferred to comparing it to true. Writing if (isEven == true) would do the same thing, but is redundant.

Warning 7.3.1.

Remember that a single = represents assignment - it says β€œgets the value”. A double equals == asks the question β€œis equal to?”.
A common mistake is to use a single = instead of a double == when comparing values. If you make this mistake, the compiler will emit a warning like the one shown below that tells you you are using an assignment operator in a place where a true/false value is expected.
test.cpp:7:10: error: suggest parentheses around assignment used as truth value [-Werror=parentheses]
    7 |     if( x = 0 ) {
      |          ~^~~

Subsection 7.3.2 The body

The body is the code that gets conditionally. Although above we have shown the body in braces ({ }), those are not strictly required if the body is only a single statement:
if (x > 0) {
    cout << "x is positive" << endl;
}

if (x > 0)
    cout << "x is positive" << endl;
The braces serve to define a block that groups multiple statements into a single one. If we want to have two statements that are both part of the body of the if, they must be made into a block with { }:
// legal, but not recommended
if (x > 0) {
    cout << "x is positive" << endl;
    cout << "that means larger than 0" << endl;
}
By convention, we indent the code that is inside a condition, whether or not it is inside braces, to clearly show that it is β€œinside” the body of the if. The compiler does not care if you indent or not, but indenting blocks makes code much easier to read.
Because indentation signals β€œthis is inside” to programers, but it meaningless to the compiler, it can be dangerous to skip braces, even when they are optional. Doing so makes it easy to accidentally add a statement to a one-line if block.
Listing 7.3.4.
With a modern compiler, you likely will get a warning about that code. But it is possible to silence the warning (like we have here) and run the code anyway.
Since there are no braces, only the first cout is part of the if statement. Here is a more accurate representation of what the compiler sees:
Listing 7.3.5.
The indentation in the first version was misleading. The second print statement is not a part of the body, and as a result, it runs no matter what. Even experienced programmers make this mistake; search the web for Apple’s β€œgoto fail” bug. To avoid this, it is a good idea to always use braces, even for one line bodies.
In all previous examples, notice that there is no semicolon at the end of the line with if (condition). That is because the body is technically part of the same statement. This is valid C++:
if (x > 0) cout << "x is positive" << endl;
But the strong convention is to write the body on a line by itself. However, it is all still one statement and there should not be a semicolon at the end of the line with the if condition. If you put a semicolon after the condition, like this:
int x = 1;
if (x % 2 == 0); {  // <--- BAD use of ;
    cout << "x is even\n";
}
The compiler sees an if statement with no body, followed by a block of code that is not a part of the conditional. It sees something more like:
int x = 1;
if (x % 2 == 0)
    ;
{ cout << "x is even\n"; }
Again, a modern compiler should offer warnings for this situation. Here, we have left the warnings enabled:
Listing 7.3.6.

Insight 7.3.2.

Make sure you know how to enable warnings for your compiler. Then pay attention to them! Most warnings are actually errors.

Checkpoint 7.3.1.

Observe the code below. β€œBigger” doesn’t print! How can you modify this so that all of the statements print?
int x = 12;
if (x == 12) {
    cout << "Equal!" << endl;
}
if (x != 13) {
    cout << "Not equal!" << endl;
}
if (x < 6) {
    cout << "Bigger!" << endl;
}
  • Change the value of x to be anything less than 6.
  • While "Bigger" would now print, the other two statements would not!
  • Change the value of x to 13.
  • Now, none of the statements would print!
  • Change the sign of the last conditional statement to x > 6.
  • Now, all of the statements would print.
  • Change the value of the return from 0 to "Bigger!"
  • main returns an int, so trying to make it return a string will cause an error.

Checkpoint 7.3.2.

What will print?
int n = 16;
int x = 4;

bool evenFlag = (n % 2 == 0);
bool plusFlag = (x > 0);

if (evenFlag) {
  cout << "n was even when I checked it ";
}

if (plusFlag) {
  cout << "x was positive when I checked it";
}
  • n was even when I checked it x was positive when I checked it
  • Great!
  • x was positive when I checked it n was even when I checked it
  • Make sure you follow the correct order of execution. Also, a space is not automatically added.
  • x was positive when I checked it
  • Take another look at the result from the modulus operator.
  • n was even when I checked itx was positive when I checked it
  • Both flags are made, But A space is after it.
  • x was positive when I checked itn was even when I checked it
  • Make sure you follow the correct order of execution.

Checkpoint 7.3.3.

What will print?
bool low_battery=true;
bool power_outage=true;

if (low_battery) {

  if (power_outage) {
      power_outage=!power_outage;
  }
  else{
      low_battery=false;
  }

  if (!power_outage) {

    if (low_battery) {
        cout << "Charging your phone" << endl;
    }
    else{
        cout << "Battery is charged" << endl;
    }

  }
  else{
    cout << "There is no power" << endl;
  }
}
  • nothing will print
  • The value of low_battery is true so we enter the first if block.
  • β€œCharging your phone”
  • correct! low_battery stays true and we set power_outage to false.
  • β€œBattery is charged”
  • low_battery is true so we don’t reach this else.
  • β€œThere is no power”
  • We change the value of power_outage to false before hand.
You have attempted of activities on this page.