Course contentsShow
← C
Lesson 208 of 1,2193. Operators and ExpressionsFree lesson

Nesting ternary operators

Nesting ternary operators

What you'll learn: How to chain ternary operators together to handle three or more possible outcomes in a single line of code.

The "Branching Paths" analogy

Imagine you are at a vending machine. If you have 2.00,yougetasoda.Ifyoudon′thave2.00, you get a soda. If you don't have 2.00, but you have $1.00, you get a water. If you have neither, you get nothing.

In the previous lesson, we learned that a basic ternary operator (condition ? true : false) is like a simple fork in the road. Chaining, or "nesting," them is like adding a second fork immediately after the first one. It allows you to check a second condition only if the first one turns out to be false.

How to build a chain

To nest ternaries, you replace the "false" part of your first operator with an entirely new ternary expression.

Think of it like this: Result = (Condition 1) ? (Value if 1 is True) : (Condition 2 ? Value if 2 is True : Value if Both are False);

The program evaluates the first condition. If it's true, it stops there. If it's false, it jumps into the second condition to keep looking for a match.

Seeing it in C

Let’s look at a concrete example that categorizes a number as positive, negative, or zero:

#include <stdio.h>

int main() {
    int number = -5;

    // Nesting allows us to check for three states
    const char* result = (number > 0) ? "Positive" 
                       : (number < 0) ? "Negative" 
                       : "Zero";

    printf("The number is %s.\n", result);
    
    return 0;
}

In this code, C first asks: "Is the number greater than zero?" Since -5 is not, it moves to the second question: "Is it less than zero?" That is true, so it selects "Negative." The final "Zero" acts as the catch-all "else" for when no other conditions are met.

A word on readability

While nesting is powerful, it can become a "wall of symbols" if you go too deep. Most developers follow a rule of thumb: if you need to check more than three conditions, it is usually better to use a standard if-else if-else block. Use nested ternaries when you want to keep simple logic concise, but always prioritize code that your teammates (and your future self) can read easily.

Key takeaway

Nesting ternary operators allows you to handle multiple conditions by placing a new ternary inside the "false" result of the previous one.