Learning C++ by Creating Games with UE4
上QQ阅读APP看书,第一时间看更新

Controlling the flow of your program

Ultimately, what we want is the code to branch in one way under certain conditions. Code commands that change which line of code gets executed next are called control flow statements. The most basic control flow statement is the if statement. To be able to code if statements, we first need a way to check the value of a variable.

So, to start, let's introduce the == symbol, which is used to check the value of a variable.

The == operator

In order to check whether two things are equal in C++, we need to use not one but two equal signs (==) one after the other, as shown here:

int x = 5; // as you know, we use one equals sign 
int y = 4; // for assignment..
// but we need to use two equals signs 
// to check if variables are equal to each other
cout << "Is x equal to y? C++ says: " << (x == y) << endl;

If you run the preceding code, you will notice that the output is this:

Is x equal to y? C++ says: 0 

In C++, 1 means true, and 0 means false. If you want the words true or false to appear instead of 1 and 0, you can use the boolalpha stream manipulator in the cout line of code, as shown here:

cout << "Is x equal to y? C++ says: " << boolalpha << 
        (x == y) << endl;

The == operator is a type of comparison operator. The reason why C++ uses == to check for equality and not just = is that we already used up the = symbol for the assignment operator! (see the More on variables section in Chapter 2, Variables and Memory). If we use a single = sign, C++ will assume that we want to overwrite x with y, not compare them.

Coding if statements

Now that we have the double equals sign under our belt, let's code the flowchart. The code for the preceding flowchart figure is as follows:

bool isHungry = true;  // can set this to false if not
                       // hungry!
if( isHungry == true ) // only go inside { when isHungry is true
{
  cout << "Preparing snack.." << endl;
  cout << "Eating .. " << endl;
}
cout << "Sitting on the couch.." << endl;
}

Tip

This is the first time we are using a bool variable! A bool variable either holds the value true or the value false.

First, we start with a bool variable called isHungry and just set it to true.

Then, we use an if statement, as follows:

if( isHungry == true )

The if statement acts like a guard on the block of code below it. (Remember that a block of code is a group of code encased within { and }.)

Coding if statements

You can only read the code between { and } if isHungry==true

You can only get at the code inside the curly braces when isHungry == true. Otherwise, you will be denied access and forced to skip over that entire block of code.

Tip

We an achieve the same effect by simply writing the following line of code:

if( isHungry )     // only go here if isHungry is true

This can be used as an alternative for the following:

if( isHungry == true )

The reason people might use the if( isHungry ) form is to avoid the possibility of making mistakes. Writing if( isHungry = true ) by accident will set isHungry to true every time the if statement is hit! To avoid this possibility, we can just write if( isHungry ) instead. Alternatively, some (wise) people use what are called Yoda conditions to check an if statement: if( true == isHungry ). The reason we write the if statement in this way is that, if we accidentally write if( true = isHungry ), this will generate a compiler error, catching the mistake.

Try to run this code segment to see what I mean:

int x = 4, y = 5;
cout << "Is x equal to y? C++ says: " << (x = y) << endl; //bad!
// above line overwrote value in x with what was in y,
// since the above line contains the assignment x = y
// we should have used (x == y) instead.
cout << "x = " << x << ", y = " << y << endl;

The following lines show the output of the preceding lines of code:

Is x equal to y? C++ says: 5
x = 5, y = 5

The line of code that has (x = y) overwrites the previous value of x (which was 4) with the value of y (which is 5). Although we were trying to check whether x equals y, what happened in the previous statement was that x was assigned the value of y.

Coding else statements

The else statement is used to have our code do something in the case that the if portion of the code does not run.

For example, say we have something else that we'd like to do in case we are not hungry, as shown in the following code snippet:

bool isHungry = true;
if( isHungry )      // notice == true is implied!
{
  cout << "Preparing snack.." << endl;
  cout << "Eating .. " << endl;
}
else                // we go here if isHungry is FALSE
{
  cout << "I'm not hungry" << endl;
}
cout << "Sitting on the couch.." << endl;
}

There are a few important things that you need to remember about the else keyword, as follows:

  • An else statement must always immediately follow after an if statement. You can't have any extra lines of code between the end of the if block and the corresponding else block.
  • You can never go into both the if and the corresponding else blocks. It's always one or the other.
    Coding else statements

    The else statement is the way you will go if isHungry is not equal to true

You can think of the if/else statements as a guard diverting people to either the left or the right. Each person will either go towards the food (when isHungry==true), or they will go away from the food (when isHungry==false).

Testing for inequalities using other comparison operators (>, >=, <, <=, and !=)

Other logical comparisons can be easily done in C++. The > and < symbols mean just what they do in math. They are the greater than (>) and less than (<) symbols, respectively. >= has the same meaning as the ≥ symbol in math. <= is the C++ code for ≤. Since there isn't a ≤ symbol on the keyboard, we have to write it using two characters in C++. != is how we say "not equal to" in C++. So, for example, say we have the following lines of code:

int x = 9;
int y = 7;

We can ask the computer whether x > y or x < y as shown here:

cout << "Is x greater than y? " << (x > y) << endl;
cout << "Is x greater than OR EQUAL to y? " << (x >= y) << endl;
cout << "Is x less than y? " << (x < y) << endl;
cout << "Is x less than OR EQUAL to y? " << (x <= y) << endl;
cout << "Is x not equal to y? " << (x != y) << endl;

Tip

We need the brackets around the comparisons of x and y because of something known as operator precedence. If we don't have the brackets, C++ will get confused between the << and < operators. It's weird and you will better understand this later, but you need C++ to evaluate the (x < y) comparison before you output the result (<<). There is an excellent table available for reference at http://en.cppreference.com/w/cpp/language/operator_precedence.