Select Page

The if-else statement in C++ is one of the basic ways to control your program flow. From tasks as simple as exiting your program early if there’s no input, to deciding what business logic to run on a massive amount of data, the if-else statement can be the right tool for the job.

In this article, we cover the basics of using the if-else statement as a C++ developer, share a few practical examples to get you started and talk about the various other options for controlling your program flow.

What Is the If-Else Statement?

Similarly to how it’s used in the English language, the if-else statement in C++ is a way to indicate direction, in the context of a C++ program. If-else is one of the flow control methods in C++, as are statements like while, for and do-while. In its simplest form, the if-else statement looks as follows:

if (condition1) {
  // code here runs when condition1 evaluates to true
} else if (condition2) {
  // code in this block runs when condition1 is false
  // but condition2 is true
} else {
  // code here runs in all other cases (e.g. when
  // condition1 and condition2 are both false)

The if-else statement runs through all its conditions from top to bottom until it reaches one that is true. Once a true condition is found, the code within the corresponding block runs and the program jumps to the code that follows the if-else statement. If no condition is true, the code in the else section is run.

You can easily nest if-else statements within other if-else statements. There’s no limit to how many conditions you can have in a single statement, but it’s considered good style to keep them to a few.

Conditions are a key part of any if-else statement, so let’s look at how they work.

Learning the Syntax of If-Else Conditions

The conditions you can use in an if-else statement range from simple logical expressions to more complex evaluations and even function calls. Every condition is evaluated as a boolean value — true or false.

Comparisons make up a common class of boolean functions in conditions. These include greater than (e > f) or lesser than (c < d), and equal (a == b) or not equal (c != d). In C++, any numerical value can be cast to a boolean, and according to the C++ standard, all values equal to zero (independent of type — be it short, int, float, double, etc) as well as null pointer values, are converted to false. All other values are converted to true. Accordingly, the number “6” would be considered true:

#include <iostream>
using namespace std;

int main() {
  if (6) {
    cout << "six is true" << endl;

// output: six is true

However, a zero is false. A string “abc” is true. An empty string is… also true! In C++, all strings evaluate to true. You can use any function call as a condition, and the result of the call will be used in the evaluation.

Once the first true condition is found, the code inside the corresponding block runs, and the program continues after the statement.

Practical Examples of If-Else Statements

Now that we know the basics, let’s jump into some practical examples of the if-else statement. Let’s say that we’re writing a program that will ask the user how many tickets they have earned at an arcade, to let them know the highest-value prize they can buy with their winnings.

Before we can get to the branching section of the code, we must first define the variable we’ll be comparing and get the user’s input:

#include <iostream>
using namespace std;
// these statements are necessary to be able to use cout and cin
. . .

  int tickets;
  cout << "How many tickets do you have so far? ";
  cin >> tickets;

. . .

Now that the program has the corresponding number of tickets, we can find out which condition is true to let the customer know what they can spend their tickets on:

if (tickets <= 5) {
  cout << "Not enough tickets — keep trying!";
else if (tickets > 5 && tickets <= 10) {
  cout << "The most expensive prize you can get is a slinky! Congratulations!";
else if (tickets > 10 tickets <= 50) {
  cout << "The most expensive prize you can get is a book! Congratulations!";
else if (tickets > 50) {
  cout << "The most expensive prize you can get is a vacuum cleaner! Congratulations!";

The cin primitive ensures safe input handling, so we don’t need to be concerned about customers inputting an invalid number. It’s a good idea, however, to let the customer know if something went wrong:

else {
  cout << "Sorry! Something went wrong. Please try inputting the number of tickets again.";

When To Use the If-Else Statement

Is if-else the best method for flow control?

It depends! In some cases, if-else is indeed best fit. For example, if you only have a few possible branches, using if-else will work just fine. The statement will generally be readable when there are a few cases, but an excessive number of cases in an if-else statement in C++ can make the program hard to read and, in some cases, slow to execute.

Another case where using if-else is a good idea is when you’re trying to structure the program in a flow that’s readily understandable. If-else conditions are explicitly called out in the code, so it’s hard for developers to miss these conditions and their possible corresponding branches. However, for if-else to work well in such cases, we recommend keeping the conditions within the statement short and clear. Including nested if-else statements or using convoluted conditions can complicate the job of the developer tasked with making changes to the logic. 

If you feel that if-else is not the right option for your particular use case, you have a few alternatives at your disposal.

Alternatives to If-Else in C++

Some alternatives to the if-else statement in C++ include loops, the switch statement, and structuring your program to not require branching.

If you’re matching against a larger set of values, the switch statement might be a fit:

switch (menu_option) {
  case 1:
    cout << "Beef wellington with asparagus";
  case 2:
    cout << "Sour chicken strips";
  case 3:
    cout << "Peanut and raisin pudding";
  case 4:
    cout << "Caesar salad";
  case 5:
    cout << "Custom pizza";

If you’re looking to write an operation that needs to be repeated a few times, definitely use a loop instead of a series of nested conditions. For example, a short loop as follows is much easier to understand than say, 30 (or 50 or 90!) if-else conditions:

int counter = 0;
do {
  cout << "Happy birthday!"
while(counter < age);

If you need to assign one of the two possible values to a variable, using a ternary operator (the ? operator) can result in clearer code than using an if-else statement:

int a = 10;
// condition ? value_when_true : value_when_false
int b = (a > 0) ? 1 : 2;
cout << b << endl;

// output: 1

C++ If-Else Statement and C++ Classes

While polymorphism is an advanced object-oriented-programming (OOP) topic in C++, it can also be a helpful alternative to if-else statements. In C++, developers can implement structures where different functions get called on an object, depending on that object’s class. For example, here’s some OOP code that uses if-else:

if (dish == Entree) cutlery = cutleryMainSet;
else if (dish == Dessert) cutlery = cutleryDessertSet;
else cutlery = defaultSet;

By using polymorphism we can simplify the code quite a bit. This code assumes that each class of dish implements its own cutlery set function:

cutlery = dish.cutlerySet();

However, polymorphic code only makes sense in more complex cases like OOP. We recommend avoiding it in simpler programs.

Become a C++ Developer

The if-else statement is just one aspect of C++ you’ll need to master as you become a C++ developer. Over time, you’ll learn when to use the if-else statement and when to consider using a different form of flow control in your program.

To kickstart your C++ journey, enroll in our expert-taught C++ Developer Nanodegree today!

Start Learning