bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths

Loading lesson path

Learn/C++/C++ Tutorial
C++•C++ Tutorial

C++ Else

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false .

Syntax

if ( condition ) {
 // block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

In the example below, the program checks the value of time . If it is less than 18, it prints "Good day". Otherwise, it prints "Good evening":

Example

int time = 20;
if (time < 18) {
  cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."

Because time is 20, the condition time < 18 is false, so the code inside the else block runs and prints "Good evening.". If time was less than 18, the program would print "Good day." instead.

Using a Boolean Variable

You can also store the condition in a boolean variable and use it in the if...else statement. This can make the code easier to read.

Example

int time = 20;
bool isDay = time < 18;
if (isDay) {
  cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."

Tip

A name like isDay makes it easy to understand what the condition means.

Previous

C++ If ... Else

Next

C++ Else If