C++ Ternary Operator

In C++, the ternary operator is a concise, inline method used to execute one of two expressions based on a condition. It is also called the conditional operator.


Ternary Operator in C++

A ternary operator evaluates the test condition and executes an expression out of two based on the result of the condition.

Syntax

condition ? expression1 : expression2;

Here, condition is evaluated and

  • if condition is true, expression1 is executed.
  • if condition is false, expression2 is executed.

The ternary operator takes 3 operands (condition, expression1 and expression2). Hence, the name ternary operator.


Example: C++ Ternary Operator

#include <iostream>
#include <string>
using namespace std;

int main() {
  double marks;

  // take input from users
  cout << "Enter your marks: ";
  cin >> marks;

  // ternary operator checks if
  // marks is greater than 40
  string result = (marks >= 40) ? "passed" : "failed";

  cout << "You " << result << " the exam.";

  return 0;
}

Output 1

Enter your marks: 80
You passed the exam.

Suppose the user enters 80. Then, the condition marks >= 40 evaluates to true. Hence, the first expression "passed" is assigned to result.

Output 2

Enter your marks: 39.5
You failed the exam.

Now, suppose the user enters 39.5. Then, the condition marks >= 40 evaluates to false. Hence, the second expression "failed" is assigned to result.

Note: We should only use the ternary operator if the resulting statement is short.

Ternary Operator Vs. if…else

1. Ternary Operator for Concise Code

The ternary operator is best for simple, inline conditional assignments where readability is not compromised. For example,

int age = 20;
string status;

status = (age >= 18) ? "Adult" : "Minor";

In this example, the condition age >= 18 is evaluated. If it's true, Adult is assigned to status; if it's false, Minor is assigned.

This is much more concise than using a full if...else statement, which would look like this:

int age = 20;
string status;

if (age >= 18) {
    status = "Adult";
} else {
    status = "Minor";
}

Here, the if...else statement takes up more lines and can clutter code when used for many simple conditional assignments.

2. if...else for Clarity in Complex Conditions

The if...else statement is better suited for complex decision-making processes and when clarity and readability are prioritized over brevity.

Suppose you need to categorize weather based on multiple conditions. Using a ternary operator with multiple conditional statements would be cumbersome and hard to read. In such cases, we use if...else.

Let's look at an example.

int temperature = 25;
string category;

if (temperature < 10) {
    category = "Cold";
} else if (temperature <= 25) {
    category = "Moderate";
} else if (temperature > 25) {
    category = "Hot";
} else {
    category = "Inhabitable";
}

3. Ternary Operator Implicitly Returns a Value

Let's look at an example to justify this point.

int number = -4;
string result;

// ternary operator assigns value directly result = (number > 0) ? "Positive Number" : "Negative Number";

Here, the ternary operator returns the value based on the condition (number>0). The returned value is stored in the result variable.

In contrast, if...else does not inherently return a value. Thus, assignment to a variable is explicit.

int number = -4;
string result;

// explicit assignment with if...else if (number > 0) result = "Positive Number"; else result = "Negative Number";

Nested Ternary Operators

It is also possible to use one ternary operator inside another ternary operator. It is called the nested ternary operator in C++.

Here's a program to find whether a number is positive, negative, or zero using the nested ternary operator.

#include <iostream>
#include <string>
using namespace std;

int main() {
  int number = 0;
  string result;

  // nested ternary operator to find whether
  // number is positive, negative, or zero
  result = (number == 0) ? "Zero" : ((number > 0) ? "Positive" : "Negative");

  cout << "Number is " << result;

  return 0;
}

Output

Number is Zero

In the above example, notice the use of ternary operators,

(number == 0) ? "Zero" : ((number > 0) ? "Positive" : "Negative");

Here,

  • (number == 0) is the first test condition that checks if number is 0 or not. If it is, then it assigns the string value "Zero" to result.
  • Else, the second test condition (number > 0) is evaluated if the first condition is false.

Note: It is not recommended to use nested ternary operators. This is because it makes our code more complex.

Before we wrap up, let’s put your knowledge of C++ ternary operator to the test! Can you solve the following challenge?

Challenge:

Write a function to return the larger of two numbers using the ternary operator.

  • Return the larger of two integers num1 and num2.
  • The ternary operator is a shorthand way of writing an if...else statement. Its syntax is:
  • condition ? trueValue : falseValue
  • For example, if num1 = 4 and num2 = 7, the output should be 7.
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges