Language: EN

cpp-condicional-ternario

What is and how to use the ternary operator in C++

The ternary operator in C++ is a concise way to perform a conditional evaluation (it is also known as the conditional operator).

It is suitable for simplifying assignments based on a condition, offering a more compact alternative to the classic if-else structure.

Basic Syntax

The ternary operator in C++ follows this basic syntax:

condition ? true_expression : false_expression
  • Condition: It is a boolean expression that evaluates to true (true) or false (false).
  • True Expression: It is the value or expression returned if the condition is true.
  • False Expression: It is the value or expression returned if the condition is false.

Basic Example

Suppose we want to determine if a number is even or odd and store the result in a variable called result. We can use the ternary operator to do this more compactly.

#include <iostream>
#include <string>

int main() {
    int number = 10;
    std::string result = (number % 2 == 0) ? "even" : "odd";
    std::cout << "The number is " << result << std::endl;
    return 0;
}

In this code, the ternary operator evaluates whether number % 2 == 0 (i.e., if the number is even). If the condition is true, result is set to "even"; if false, it is set to "odd". This approach reduces the need for a more extensive if-else structure.

Nesting the Ternary Operator

The ternary operator can be nested to handle multiple conditions.

#include <iostream>
#include <string>

int main() {
    int number = 10;

    std::string result = (number > 0) ? "positive" :
                         (number < 0) ? "negative" : "zero";

    std::cout << "The number is " << result << std::endl;
    return 0;
}

Here,

  • It first evaluates whether number is greater than 0
  • If true, result is set to "positive"
  • If false, it evaluates whether the number is less than 0
  • If this is also false, result is set to "zero"

Excessive nesting can affect code readability. So do not abuse it

Practical Examples

These examples illustrate how to use the ternary operator to simplify code. It is not always the best option for all situations, especially if the logic is complex. In such cases, if-else structures may offer better clarity.