Course contentsShow
← C
Lesson 252 of 1,2194. Control FlowFree lesson

The ternary operator (?:) as a shortcut

The ternary operator (?:) as a shortcut

What you'll learn: How to use the ternary operator to write concise, single-line conditional expressions for simple decision-making.

The "Fork in the Road" shortcut

Up to now, you have used if-else blocks to control the flow of your programs. While reliable, if-else statements can feel bulky when all you want to do is assign a value to a single variable based on a simple condition.

Think of the ternary operator as a grammatical shortcut. If a standard if-else is a full paragraph explaining two options, the ternary operator is a quick sentence like: "Is it raining? If yes, take an umbrella; if no, leave it." It is the only operator in C that takes three parts (operands), which is why it is called "ternary."

Syntax and Logic

The operator uses two symbols: the question mark (?) and the colon (:). The structure looks like this:

condition ? value_if_true : value_if_false;

  1. The Condition: A test that results in true or false (e.g., x > 10).
  2. The Question Mark: Asks, "Is this condition true?"
  3. The First Value: The result if the condition is true.
  4. The Colon: Separates the two possible outcomes.
  5. The Second Value: The result if the condition is false.

Seeing it in Action

Imagine you are writing a program for a movie theater that gives a discount to anyone under 18. Here is how you might compare the traditional if-else approach with the ternary shortcut:

#include <stdio.h>

int main() {
    int age = 16;
    double ticketPrice;

    // The traditional way
    if (age < 18) {
        ticketPrice = 10.0;
    } else {
        ticketPrice = 15.0;
    }

    // The ternary shortcut way
    double discountPrice = (age < 18) ? 10.0 : 15.0;

    printf("Price: $%.2f", discountPrice);
    
    return 0;
}

When to use it

The ternary operator is excellent for simple assignments, like determining the maximum of two numbers or choosing a string to print. However, avoid "nesting" them (putting a ternary inside another ternary). While the computer can read it, it becomes a headache for humans. Use this shortcut to keep your code clean and readable, not to make it a riddle.

Key takeaway

The ternary operator (?:) is a compact way to choose between two values based on a condition, replacing simple if-else blocks with a single line of code.