Video Coming Soon...

Created by Zed A. Shaw Updated 2024-11-15 13:50:32

12: if-statements

You'll now learn how to make decisions in your code, but using an if-statement. An if-statement is a way to use Boolean Tests from the previous exercise to change the way your code runs. If something is true, then one block of code runs, and if it's not then other blocks of code run. I think the best way to understand this concept is to simply jump right in.

What Is A Jump?

The easiest way to understand a jump is to view your programming so far as "straight line." Your code starts at the main() line, then processes each line until it hits the return 0 line. Easy enough, but now, what if I want to jump over some lines? Create a file named ex12a.cpp and enter in this little bit of code:

View Source file ex12a.cpp Only

#include <iostream>
#include <fmt/core.h>

using namespace std;
using namespace fmt;

int main() {
  println("I will run.");

  goto skipped;

  println("I will NOT run.");

skipped:
  println("I will also run.");

  return 0;
}

When you run this code you'll see that the line println("I will NOT run.") won't actually run. Let's walk through this code to understand it:

8
This line will run and print I will run.
10
goto skipped tells C++ to jump to the line with skipped: on it, which is line 14.
12
This line actually won't run because of the goto skipped on line 10. It is "jumped" over.
14
This is where the goto skipped line lands, and there's nothing on there, it just is a landing point.
15
This line will run and prints I will also run. as it comes right after the skipped: label.
17
Then the program ends like normal.

This isn't too useful yet, but the important thing to understand is you can control where C++ goes, and this is called "flow control."

Jumps and Tests

Now I want you to imagine if you could do a test with boolean operators, and then jump only if that test is true. This code won't actually work but imagine it's something like this:

int i = 100;

bool do_jump = i < 1000;

if(do_jump) goto skipped;

println("do_jump is FALSE");

skipped:
println("do_jump is TRUE");

This code is similar to the ex12a.cpp code, but it's using a fake "test then jump" syntax of if TEST goto LABEL; This doesn't actually exist, but this is also closer to how your computer really does control flow.

In C++ though this kind of code is considered "low class" as it is difficult to know where it goes visually. The better form is C++'s if-statement.

if-statement Syntax

In C++ you do the same thing using this format, but notice it's reversed from my fake if TEST goto code so that the true part is first, false is second:

if(TEST) {
   // this is true
} else {
   // this is false
}

This reads like English, where you might say, "If this person is guilty, convict them; else set them free." How it works is like this:

  1. First, the TEST is calculated to determine if it's true or false. This will be a boolean test from Exercise 11.
  2. If that TEST is true, then the code inside the { } with // this is true will run, and the else block will be skipped!
  3. However, if TEST is false then that first block // this is true will be skipped! and code will jump to the else {} part that has // this is false.

Study this for a bit, and then let's add one more little part that completes the if-statement by adding an else-if clause:

if(TEST) {
  // this is true
} else if(TEST_OTHER) {
  // this runs if TEST_OTHER true
} else {
  // everything is false
}

This only adds one more test and another block. The else-if will run only if the previous if(TEST) failed, and if that else-if fails, then finally the else runs at the end.

An important part of this is you can have as many else if you want after the first if and before the final else. If you need to test 20 conditions then you just write many else if tests. Also, probably rethink that code because 20 is a lot.

The Code

You will now have a chance to study this code which uses many if/else if/else examples, combined with variables and math:

View Source file ex12.cpp Only

#include <iostream>
#include <fmt/core.h>

using namespace std;
using namespace fmt;

int main() {
  int height = (6*12) + 2;
  int age = 50 * 12;
  const int is_tall = 6*12;
  const int is_old = 100; // no cap

  if(height > is_tall) {
    println("You are considered tall.");
  } else if(height == is_tall) {
    println("You could be if you lied about your height.");
  } else {
    println("You are considered short.");
  }

  if(age > is_old) {
    println("You are considered old.");
  } else if(age == is_old) {
    println("You are still considered old.");
  } else if(age > is_old / 2) {
    println("Most people still think you're old.");
  } else {
    println("You're considered not old.");
  }

  return 0;
}

Typing this code in a "bit at a time" can be tricky because you can't just enter the first line of an if-statement and make it work. A better way is to use the "taco method," which means to type the { } braces, then fill them in. First type this:

if(height > is_tall) {
}

That creates the "shell" of the taco with {}, then fill in the contents of the {} and add the next part in the same way, until the if-statement is done and working.

Break It

Now we get some reall good ways to break things. The syntax for C++'s if-statements is insanely error prone. In fact, a massive number of bugs in C and C++ projects comes from the way programmers insist on writing if-statements. Try some of these:

  1. You can write if(age > is_old) without the {} wrapping the contents. Since there's only one line it'll work, but then later someone will come along and add another line and now you get a bug similar to ones found in OpenSSL.
  2. You can be "clever" and not use else if, but instead just use a sequence of if() with no {} and no else. So many bugs to be created with this "clever" mechanism.
  3. Remember that goto skipped? I now give you permission to abuse that to craft the most glorious underhanded code you can. Combining goto with if() that has no {} and you've got the makings of some very hard to spot defects.

Have fun. There's so many ways to mess up this code, and you'll learn a lot by doing so.

Further Study

  1. You should be combining everything you know so far to expand this code and make it more interesting. Use math, boolean expressions, &&, ||, printing, and everything else you know.
  2. You should also be using if-statements to change variables for later if-statements.
Previous Lesson Next Lesson

Register for Learn C++ the Hard Way

Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.