Ternary Operator in C

The ternary operator in C is a shorthand way to write an if-else statement. It is also called the conditional operator and is represented by the symbols ? :. It allows you to evaluate a condition and return one of two values based on whether the condition is true or false.

Ternary Operator in C

Syntax:

condition ? expression_if_true : expression_if_false;
  • condition → An expression that evaluates to either true (non-zero) or false (zero).
  • expression_if_true → The value or expression that is executed if the condition is true.
  • expression_if_false → The value or expression that is executed if the condition is false.

Example 1: Basic Usage

#include <stdio.h>

int main() {
    int a = 10, b = 20;
    int max = (a > b) ? a : b;  // If a > b, max = a; otherwise, max = b
    printf("Maximum value is: %d\n", max);
    return 0;
}

Output:

#include <stdio.h>

int main() {
    int num = 7;
    (num % 2 == 0) ? printf("Even\n") : printf("Odd\n");
    return 0;
}

Output:

Precedence and Associativity:

  • Precedence: Lower than arithmetic and relational operators
  • Associativity: Right to left

Practice Questions:

  1. a=10?0?2:3:1; what is the value of a?
  2. a=2?3?4:5:7?6:8; what is the value of a?
  3. a=0?7?2:3:4; what is the value of a?
  4. a=3:2:1?4:6; what is the value of a?
  5. a=3?2?5:4?6:7:1; what is the value of a?

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow