Ternary Operator in C: What Is Ternary Operator in C & Inline Usage

The conditional expression is also known in c as the ternary operator and provides a concise way of selecting between two alternatives. To answer what is ternary operator in c, the ternary operator in c is the only operator in the C programming language that takes three operands: condition ? expression_if_true : expression_if_false. The ternary operator in c is perfect for assigning default values, clamping sensor inputs or for choosing singular or plural labels in printf calls and avoiding the need to write a four-line if/else statement to the same effect, as long as you're sure to not nest ternary expressions and make the code less readable.

Ternary Operator in C (?:): Conditional Expression Guide & Examples — Technical Overview

The conditional expression is also known in c as the ternary operator and provides a concise way of selecting between two alternatives. To answer what is ternary operator in c, the ternary operator in c is the only operator in the C programming language that takes three operands: condition ? expression_if_true : expression_if_false. The ternary operator in c is perfect for assigning default values, clamping sensor inputs or for choosing singular or plural labels in printf calls and avoiding the need to write a four-line if/else statement to the same effect, as long as you're sure to not nest ternary expressions and make the code less readable.

#include <stdio.h>

int main(void) {
    int items = 1;
    int clamped = (items < 0) ? 0 : items;
    printf("Selected %d %s\n", clamped, (clamped == 1) ? "item" : "items");
    return 0;
}

Runnable C example

#include <stdio.h>

int main(void) {
    int items = 1;
    int clamped = (items < 0) ? 0 : items;
    printf("Selected %d %s\n", clamped, (clamped == 1) ? "item" : "items");
    return 0;
}

Open example in compiler

Expected Output

Selected 1 item