Skip to content

If-Else Statements

The if-else statement allows a program to choose between two paths based on a condition. If the condition evaluates to true, one block of code is executed; otherwise, the alternative block is executed.

A flow chart that shows a decision based flow chart

An if-else statement in C++ follows this basic structure:

if (logical expression) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}

The else block is optional in C++. If you only need to execute code when the condition is true, you can omit the else statement:

if (condition) {
// Code to execute if condition is true
}

You can nest if-else statements within one another to handle multiple conditions. This structure allows your program to make more complex decisions by checking additional conditions inside the if or else blocks. For example:

if (true) {
// Do something...
if (true) {
// Do something...
} else {
// Do something...
}
} else {
// Do something...
}

If you have more than 2 cases you can use as many else if statements as you need:

if (condition1) {
// Do something
} else if (condition2) {
// Do something
} else if (condition3) {
// Do something
} else {
// Do something
}

You can find a list of general requirements that apply to a control structure like if-else statements in the control structures page. The following is an example of an if-else statement using code instead of placeholders:

if (account < price) {
cout << "Insufficient funds" << endl;
} else {
account -= price;
cout << "Thank you for your order!" << endl;
}

You can omit the braces if your code block does not contain an else statement and consists of only a single line. If the statement is short enough, you can even place it all on one line:

if (highest_score) cout << "You have the #1 rank!" << endl;

The following is an example of an incorrectly placed opening brace:

if (true)
{
cout << true << endl;
} else {
cout << false << endl;
}

The next incorrect style shows an incorrectly placed else statement:

if (true) {
cout << true << endl;
}
else {
cout << false << endl;
}

The final incorrect style shows missing braces, unfortunately the error message does not mention missing braces on both statements:

if (true)
cout << true << endl;
else
cout << false << endl;

Most of the operators we’ve encountered so far, such as +, -, *, /, %, = and comparison operators like == and !=, are binary operators, meaning they take two operands.

The conditional operator (?:), also known as the ternary operator, is unique because it takes three operands. The syntax is:

condition ? true_action : false_action

They are useful for variables whose values require a condition:

int x = 1, y = 5;
int max = (x > y) ? x : y;

In this example, max will hold the value of y because the condition x > y is false. The ternary operator is a compact alternative to if- else statements for simple conditional assignments.