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, providing 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

Let’s 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 checks whether the number is less than 0
  • If this is also false, result is set to "zero"

Excessive nesting can affect code readability. So don’t abuse it

Practical Examples

Comparing two numbers and determining the greater one

To compare two numbers and determine which is greater, we can use the ternary operator instead of a more extensive if-else structure.

#include <iostream>

int main() {
    int a = 5;
    int b = 8;
    int greater = (a > b) ? a : b;

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

In this example, greater is assigned the value of a if a is greater than b; otherwise, it is assigned the value of b.

Value Assignment

The ternary operator is useful for assigning a value based on a simple condition in a single line of code.

#include <iostream>
#include <string>

int main() {
    int age = 20;
    std::string category = (age >= 18) ? "adult" : "minor";
    std::cout << "The person is " << category << std::endl;
    return 0;
}

Here, category is set to "adult" if age is greater than or equal to 18; otherwise, it is set to "minor".

Return Value in Methods

The ternary operator can also be used to determine the return value of a method based on a condition.

#include <iostream>
#include <string>

std::string getGreeting(bool isFormal) {
    return isFormal ? "Good morning, sir/madam" : "Hello";
}

int main() {
    bool isFormal = true;
    std::cout << getGreeting(isFormal) << std::endl;
    return 0;
}

In this case, the function getGreeting returns "Good morning, sir/madam" if isFormal is true; otherwise, it returns "Hello".

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.