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

Syntax of `? :`

Syntax of ? :

What you'll learn: How to use the ternary operator as a compact, one-line alternative to simple if-else statements.

The "Shortcut" Operator

In programming, we often face a fork in the road: if a condition is true, do one thing; if it’s false, do another. While a standard if-else block is great for complex logic, it can feel bulky for simple decisions.

The ternary operator (? :) is C’s only operator that takes three parts. Think of it like a quick roadside sign. Instead of pulling over to read a map (a full if-else block), you glance at the sign and immediately know which lane to take. It allows you to evaluate a condition and return a value all in a single expression.

Anatomy of the Ternary

The syntax follows a specific pattern: condition ? value_if_true : value_if_false;

  1. The Question (?): This follows your condition. It’s like asking the computer, "Is this true?"
  2. The Colon (:): This acts as the separator between your two possible outcomes.

Imagine you are checking if a user is an adult. If their age is 18 or over, they are a "Member"; otherwise, they are a "Guest."

#include <stdio.h>

int main() {
    int age = 20;
    
    // If age >= 18 is true, "Member" is assigned.
    // If age >= 18 is false, "Guest" is assigned.
    const char* status = (age >= 18) ? "Member" : "Guest";

    printf("User status: %s", status);

    return 0;
}

Why Use It?

The primary goal of the ternary operator is conciseness. In the example above, a traditional if-else would have taken five or six lines of code. With the ternary operator, we condensed the logic into a single line that is easy to read at a glance.

However, a word of caution: only use this for simple "either-or" logic. If you start nesting ternary operators inside one another, your code becomes a "riddle" that is hard for other programmers to solve. If the logic feels heavy, stick to a regular if-else.

Key takeaway

The ternary operator ? : provides a compact way to choose between two values based on a condition.