How to use the ternary operator in C++

Overview

In C++, the ternary operator is used to replace a multiline if-else code with a single line. It’s a shorthand if-else statement as it contains three operands.

Syntax

variable = (condition) ? expressionTrue : expressionFalse;

In the code above, the expressionTrue represents a block of code or statement to be executed if the condition given is true. The expressionFalse will execute if the given condition is false.

Next, let’s illustrate the practicality of the ternary operator using a few code examples.

Example 1: How to use the if-else statement

#include <iostream>
using namespace std;
int main() {
if (1 > 2) {
cout << "1 is greater than 2";
} else {
cout << "1 is less than 2";
}
return 0;
}

Explanation

  • Lines 5 and 6: We use if to write a condition—if 1 is greater than 2, the code executes the "1 is greater than 2" statement.
  • Line 7 and 8: We use else to execute another statement if the condition is false.

We use multiple lines of codes in writing the program above. To avoid such situations, we use the ternary operator.

Example 2: How to use the ternary operator

#include <iostream>
#include <string>
using namespace std;
int main() {
int a = 1;
string result = (a > 2) ? "1 is greater than 2" : "1 is less than 2";
cout << result;
return 0;
}

Explanation

  • Line 6: We create an integer variable a.
  • Line 7: We use the ternary operator to pass a condition—if the value of the variable a is greater than 2, the code executes the expressionTrue statement. Otherwise, it executes the expressionFalse statement.

As shown in the code above, the ternary operator reduces multiple lines of code to a single line of code.