Learning C++: Part 4: Conditional Statements

Learning C++


Conditional Statements

In C++, each statement is either true or false. This can seem confusing, as the use of the statement “int a = 5;” does not seem to have a connection to thinking of true or false. Yet, in C++, this is always true.

The ability of statements, instructions, to have either true or false outcomes means that it is possible to create conditional statements that can be used do different instructions depending on if the statement is true or false.

Comparing Values

To move away from simply stating things, values can also be compared. This allows for testing if one value is less than another, or if two variables have the same value.

To compare two values in C++, the if keyword is used. Looking and working like a function, an if-statement has the if keyword, open and closing parentheses, and open and closing curly brackets.

The entries in the parentheses are what is being compared. Depending on the outcome, the condition will be either true or false. That is, either one value will be less than another another, greater than, or be the result will settle into either simply true or false.

Common Types of Comparisons

  • < (less-than)
  • > (greater-than)
  • <= (less-than-or-equal-to)
  • >= (greater-than-or-equal-to)

The instructions inside of the curly brackets is what is run if the condition is true. If the statement is not true, the code is not run.

Else

For those situations where one set of code is run if a statement is true and another set of code is run if the statement is not, the else keyword can be used.

The else keyword allows for enclosing a set of instructions for situations where the previous if statement is not true. The keyword else is only used as part of a pair with an if statement.

Working with Booleans

As was introduced as part of an earlier section on variables, one of the types of values in C++ is a Boolean. As a review, a Boolean is either true or false.

Because statements are either true or false, this also means that a variable of type bool can be a statement by itself. This also means it can be used inside of an if statement.

Booleans have some of their own special operations. Because they only have the values true or false, three new operations are important as they apply to Booleans and conditional statements: AND, NOT, and OR.

AND

Two statements (or Boolean values) paired together can use the operator AND to see if both statements are true. In C++, the AND operator is two ampersands: &&.

NOT

The not operator, an exclamation mark in front of a statement, negates the value. That is, because Boolean values are either true or false, this switches it between them.

OR

Like the AND operator, the OP operator tests to see if one of them is true. It is generally read as “if X OR Y is true” where X and Y are statements. In C++, the operator is two bars: ||.

Play with example on Repl.it!