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

Ternary as an expression

Ternary as an expression

What you'll learn: How the ternary operator functions as a single value that can be assigned or embedded directly into other code.

It’s a value, not a container

In previous lessons, you used if-else statements to control the flow of your program. An if statement is like a set of tracks at a train station; it directs the train down one path or another. However, an if statement itself doesn't "equal" anything. You cannot say int x = if(a > b)....

The ternary operator (? :) is different. It is an expression, meaning it evaluates to a single value. Think of it like a vending machine: you put in a condition, and it spits out a result. Because it results in a value, you can put it anywhere a number or variable would go.

Direct Assignment

The most common use for the ternary operator is to initialize a variable based on a condition in a single line. Instead of creating a variable and then changing it inside an if block, you can define the value immediately.

#include <stdio.h>

int main() {
    int score = 85;
    
    // The ternary expression evaluates to either 'P' or 'F'
    // That single value is then assigned to 'grade'
    char grade = (score >= 50) ? 'P' : 'F';

    // You can even embed it directly into a function call
    printf("Result: %s\n", (grade == 'P') ? "Success" : "Failure");

    return 0;
}

Why this matters

Because the ternary operator is an expression, it allows for "Inline Logic." In the example above, we didn't just use it to set the grade variable; we actually put a second ternary operator directly inside the printf function.

C sees (grade == 'P') ? "Success" : "Failure" and resolves it down to a single string before printf even runs. This keeps your code concise. You are essentially telling the computer: "Pick one of these two values and hand it off to the next part of the program." Just remember that while you can nest expressions inside each other, keeping them simple ensures your code remains readable to others.

Key takeaway

Unlike an if statement, a ternary expression resolves to a specific value that can be assigned to variables or passed into functions.