Conditional (Ternary) Operator in C

The conditional operator, also called the ternary operator, is a shorthand way of writing an if-else statement in C. It takes three operands and uses the syntax: condition ? expression_if_true : expression_if_false.

Syntax

condition ? expression_if_true : expression_if_false;

Example

int a = 10, b = 20; int max = (a > b) ? a : b; // max will be 20

How it Works

  • If the condition is true, the first expression is evaluated.
  • If the condition is false, the second expression is evaluated.
  • The result of the evaluated expression is returned.

Advantages

  • Shorter code compared to if-else statements
  • Useful in assignments and return statements
  • Makes simple conditional decisions concise

Common Mistakes

  • Overusing ternary operators for complex conditions (reduces readability)
  • Confusing ? and : placement
  • Using expressions with side effects inside ternary operator
  • Assuming it can replace all if-else structures