Ternary Operator

The ternary operator is a shorthand way to write simple if-else statements in C. It's called "ternary" because it involves three operands, making it the only three-operand operator in C.

Syntax

condition ? value_if_true : value_if_false

Think of it as asking a question: "Is this condition true? If yes, use this value; if no, use that value."

How It Works

The ternary operator evaluates a condition:

  • If the condition is true, it returns the first value (after ?)
  • If the condition is false, it returns the second value (after :)

Basic Example

#include <stdio.h>

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

This is equivalent to:

if (a > b) {
    max = a;
} else {
    max = b;
}

More Examples

Finding Absolute Value

int num = -15;
int absolute = (num < 0) ? -num : num;
printf("Absolute value: %d\n", absolute);  // Output: 15

Checking Even or Odd

int number = 7;
printf("%d is %s\n", number, (number % 2 == 0) ? "even" : "odd");
// Output: 7 is odd

Grade Assignment

int score = 85;
char grade = (score >= 90) ? 'A' : (score >= 80) ? 'B' : (score >= 70) ? 'C' : 'F';
printf("Grade: %c\n", grade);  // Output: Grade: B

Nested Ternary Operators

You can nest ternary operators, but be careful not to make your code too complex:

int x = 15;
char* result = (x > 20) ? "High" : (x > 10) ? "Medium" : "Low";
printf("Result: %s\n", result);  // Output: Result: Medium

When to Use Ternary Operator

Good for:

  • Simple conditional assignments
  • Short, readable conditions
  • Inline decisions

Avoid when:

  • The logic is complex
  • Multiple statements are needed
  • It makes code harder to read

The ternary operator is a powerful tool for writing concise code, but remember: clarity is more important than brevity. Use it when it makes your code cleaner and easier to understand!