Skip to content

C Ternary Operator (?:)

Updated 6 min read Aimerscrew

Many decisions in a program aren't about what to do but about which value to use: free shipping or a fee, "item" or "items", the bigger of two numbers. The C ternary operator ?: picks one of two values in a single, compact expression. In this lesson, you'll learn its syntax, when it makes code clearer, and when a regular if else is the better choice.

🌍 Real-life example

At checkout, an online store shows one line: "Shipping: FREE" or "Shipping: $4.99". The rule is a single question with two possible answers: is the cart total at least $50? The ternary operator is built for exactly this "question, answer if yes, answer if no" pattern.

What is the ternary operator in C?

The ternary operator is the only C operator that takes three operands, which is where the name "ternary" comes from. It's also called the conditional operator. Its syntax is:

condition ? value_if_true : value_if_false

C evaluates the condition first. If it's non-zero (true), the whole expression becomes value_if_true. If it's 0 (false), it becomes value_if_false. Only the chosen side is evaluated; the other one is skipped completely.

#include <stdio.h>

int main(void) {
    int a = 17;
    int b = 42;

    int larger = (a > b) ? a : b;

    printf("The larger number is %d\n", larger);
    return 0;
}
The larger number is 42

Read the middle line as: "Is a greater than b? If yes, use a; otherwise, use b." Since 17 is not greater than 42, larger gets 42.

The expression shipping = (total >= 50) ? 0.00 : 4.99 split into its three parts: condition, value if true and value if false. With a total of 64.00 shipping gets 0.00; with a total of 35.50 shipping gets 4.99.
The condition decides which of the two values the whole expression becomes.

Ternary operator vs if else

The ternary version of "find the larger number" does the same job as this if else, in one line instead of six:

int larger;
if (a > b) {
    larger = a;
} else {
    larger = b;
}

The key difference: an if statement chooses which code to run, while the ternary operator is an expression that produces a value. That means you can use it in places where an if statement can't go, such as inside a printf() call or when initializing a constant:

const int fee = isMember ? 0 : 5;   // a const must get its value right away
Ternary ?:if / else
What it isAn expression that gives a valueA statement that runs code
Best forChoosing between two simple valuesRunning several lines, or many branches
Can go inside printf() or an initializerYesNo
Readability with many conditionsGets hard quicklyStays clear

Real-world example: "item" or "items"

Nothing looks sloppier than "You have 1 items". Because the ternary operator gives a value, you can drop it straight into a printf() argument to choose the right word. The %s specifier prints text; you'll learn more about text in C strings.

#include <stdio.h>

int main(void) {
    int count = 1;
    printf("You have %d %s in your cart.\n", count, (count == 1) ? "item" : "items");

    count = 3;
    printf("You have %d %s in your cart.\n", count, (count == 1) ? "item" : "items");

    return 0;
}
You have 1 item in your cart.
You have 3 items in your cart.

Real-world example: free shipping

Here's the store rule from the diagram, applied to two different carts:

#include <stdio.h>

int main(void) {
    double cartA = 64.00;
    double cartB = 35.50;

    double shippingA = (cartA >= 50.0) ? 0.00 : 4.99;
    double shippingB = (cartB >= 50.0) ? 0.00 : 4.99;

    printf("Cart A: $%.2f + shipping $%.2f = $%.2f\n", cartA, shippingA, cartA + shippingA);
    printf("Cart B: $%.2f + shipping $%.2f = $%.2f\n", cartB, shippingB, cartB + shippingB);

    return 0;
}
Cart A: $64.00 + shipping $0.00 = $64.00
Cart B: $35.50 + shipping $4.99 = $40.49

More handy one-liners

A few patterns you'll see again and again in real C code:

#include <stdio.h>

int main(void) {
    int x = -12;
    int distance = (x < 0) ? -x : x;            /* absolute value */

    int scoreA = 71;
    int scoreB = 68;
    int lowerScore = (scoreA < scoreB) ? scoreA : scoreB;   /* minimum */

    int stock = 0;

    printf("Distance from zero: %d\n", distance);
    printf("Lower score: %d\n", lowerScore);
    printf("Status: %s\n", stock > 0 ? "In stock" : "Sold out");

    return 0;
}
Distance from zero: 12
Lower score: 68
Status: Sold out

Can you nest ternary operators?

Yes. The value on either side can itself be another ternary expression. This lets you pick from three or more values. A cinema charges $8.50 for children under 12, $9.00 for seniors aged 65 or over, and $13.75 for everyone else:

#include <stdio.h>

int main(void) {
    int age = 70;

    double price = (age < 12)  ? 8.50
                 : (age >= 65) ? 9.00
                 : 13.75;

    printf("Age %d pays $%.2f\n", age, price);
    return 0;
}
Age 70 pays $9.00

The ternary operator groups from right to left, so this reads like an else if chain: "under 12? 8.50; otherwise, 65 or over? 9.00; otherwise 13.75". Laying it out on separate lines, one condition per line, keeps it readable.

⚠️ Be careful

One level of nesting, neatly formatted, is fine. Two or more levels squeezed onto one line, like a ? b ? c : d : e, is a puzzle for whoever reads it next. When in doubt, use an if else chain.

Ternary operator precedence

The ternary operator has very low precedence: lower than arithmetic, comparison and logical operators, but higher than assignment. So in max = a > b ? a : b;, C compares first, then picks a value, then assigns it. That works without parentheses, but wrapping the condition, as in (a > b) ? a : b, makes the three parts easier to see. When a ternary sits inside a bigger calculation, put parentheses around the whole thing: total = price + (isMember ? 0 : 5);.

Common mistakes with the ternary operator

1. Using it for actions instead of values

(balance < 0) ? printf("Overdrawn\n") : printf("OK\n");

This compiles, but it hides a decision about which code to run inside an expression. Use an if else for actions and keep the ternary for choosing values.

2. Mixing types in the two branches

Both results are converted to one common type. In (stock > 0) ? stock : 0.5, the int branch is converted to double, so the result is always a double. Printing it with %d is wrong: GCC warns about the format, and the program prints a garbage value. Keep both branches the same type.

3. Forgetting parentheses in a bigger expression

total = price + isMember ? 0 : 5; is read as (price + isMember) ? 0 : 5, so total ends up as 0 or 5 instead of a price. Wrap the ternary in parentheses.

4. Writing a ternary nobody can read

Short and clever isn't the goal; clear is. If a ternary needs a comment to explain it, rewrite it as an if else.

Practice exercise

🏋️ Try it yourself

A phone battery is at 15 percent. Using the ternary operator, store 'Y' in a char called lowPower if the level is below 20, otherwise 'N'. Then print Battery: 15% (low power mode: Y). Hint: write %% to print a percent sign.

Show solution
#include <stdio.h>

int main(void) {
    int battery = 15;
    char lowPower = (battery < 20) ? 'Y' : 'N';

    printf("Battery: %d%% (low power mode: %c)\n", battery, lowPower);
    return 0;
}
Battery: 15% (low power mode: Y)

What's next?

You can now make decisions with if else, switch and the ternary operator. Next, learn how to repeat code with the C for loop.

Key takeaways

  • The ternary operator condition ? a : b gives a if the condition is true (non-zero) and b otherwise.
  • It is an expression that produces a value, so it can go inside printf() or a const initializer.
  • Only the chosen branch is evaluated; the other is skipped.
  • Use it for choosing between two simple values and an if else for running blocks of code.
  • It groups right to left, so nested ternaries read like an else if chain; keep nesting shallow and formatted.
  • Its precedence is low, so wrap it in parentheses when it is part of a larger expression.

Frequently asked questions

What is the ternary operator in C?

It is the conditional operator ?:, written condition ? value_if_true : value_if_false. It evaluates the condition and gives back one of the two values. It is the only C operator with three operands.

Is the ternary operator faster than if else in C?

Not in any meaningful way. Modern compilers usually produce the same machine code for both. Choose the ternary for readability when picking between two values, not for speed.

Can I nest ternary operators in C?

Yes. Because the operator groups from right to left, a ? x : b ? y : z works like an else if chain. Keep it to one level and put each condition on its own line, or use if else instead.

Can the ternary operator call functions?

Yes, each branch can be any expression, including a function call, and only the chosen one runs. Still, for actions such as printing different messages, an if else statement is usually clearer.

Why is it called the ternary operator?

Ternary means made of three parts. Most operators are unary (one operand, like !x) or binary (two operands, like a + b), while ?: takes three: the condition and the two possible values.