Ternary Operators

Introduction

The ternary operator (?:) is a compact conditional operator in C that provides a shorthand way to write simple if-else statements. It’s called “ternary” because it takes three operands: a condition, a value if true, and a value if false. This operator makes code more concise for simple conditional assignments.

Key Concepts

Conditional Expression: condition ? value_if_true : value_if_false Compact Syntax: Replaces simple if-else statements Return Value: Always returns one of the two values based on condition

Basic Syntax

Simple Example

#include <stdio.h>
int main() {
    int a = 10, b = 20;
    
    // Using ternary operator
    int max = (a > b) ? a : b;
    printf("Maximum: %d\n", max);
    
    // Equivalent if-else statement
    int max2;
    if (a > b) {
        max2 = a;
    } else {
        max2 = b;
    }
    printf("Maximum (if-else): %d\n", max2);
    
    return 0;
}

Direct Usage in printf

#include <stdio.h>
int main() {
    int score = 85;
    
    printf("Result: %s\n", (score >= 60) ? "Pass" : "Fail");
    
    int age = 17;
    printf("Status: %s\n", (age >= 18) ? "Adult" : "Minor");
    
    return 0;
}

Practical Examples

Finding Minimum and Maximum

#include <stdio.h>
int main() {
    int x = 15, y = 25, z = 10;
    
    // Find maximum of two numbers
    int max = (x > y) ? x : y;
    printf("Max of %d and %d: %d\n", x, y, max);
    
    // Find minimum of two numbers
    int min = (x < y) ? x : y;
    printf("Min of %d and %d: %d\n", x, y, min);
    
    // Find maximum of three numbers (nested ternary)
    int max3 = (x > y) ? ((x > z) ? x : z) : ((y > z) ? y : z);
    printf("Max of three: %d\n", max3);
    
    return 0;
}

Grade Assignment

#include <stdio.h>
int main() {
    int marks = 78;
    
    char grade = (marks >= 90) ? 'A' : 
                 (marks >= 80) ? 'B' : 
                 (marks >= 70) ? 'C' : 
                 (marks >= 60) ? 'D' : 'F';
    
    printf("Marks: %d, Grade: %c\n", marks, grade);
    
    return 0;
}

Even/Odd Check

#include <stdio.h>
int main() {
    int number = 23;
    
    printf("%d is %s\n", number, (number % 2 == 0) ? "even" : "odd");
    
    // Multiple numbers
    int nums[] = {10, 15, 20, 33, 44};
    for (int i = 0; i < 5; i++) {
        printf("%d: %s\n", nums[i], (nums[i] % 2 == 0) ? "even" : "odd");
    }
    
    return 0;
}

Absolute Value

#include <stdio.h>
int main() {
    int x = -15;
    int absolute = (x < 0) ? -x : x;
    
    printf("Absolute value of %d is %d\n", x, absolute);
    
    // Test with different values
    int values[] = {10, -5, 0, -20, 7};
    for (int i = 0; i < 5; i++) {
        int abs_val = (values[i] < 0) ? -values[i] : values[i];
        printf("|%d| = %d\n", values[i], abs_val);
    }
    
    return 0;
}

Nested Ternary Operators

Multiple Conditions

#include <stdio.h>
int main() {
    int temperature = 25;
    
    char* weather = (temperature > 30) ? "Hot" :
                   (temperature > 20) ? "Warm" :
                   (temperature > 10) ? "Cool" : "Cold";
    
    printf("Temperature: %d°C - %s\n", temperature, weather);
    
    return 0;
}

Age Category

#include <stdio.h>
int main() {
    int age = 25;
    
    char* category = (age < 13) ? "Child" :
                    (age < 20) ? "Teenager" :
                    (age < 60) ? "Adult" : "Senior";
    
    printf("Age: %d, Category: %s\n", age, category);
    
    return 0;
}

Using with Functions

Function Return Values

#include <stdio.h>

int max(int a, int b) {
    return (a > b) ? a : b;
}

int sign(int x) {
    return (x > 0) ? 1 : (x < 0) ? -1 : 0;
}

int main() {
    printf("Max of 10 and 20: %d\n", max(10, 20));
    
    printf("Sign of 15: %d\n", sign(15));
    printf("Sign of -5: %d\n", sign(-5));
    printf("Sign of 0: %d\n", sign(0));
    
    return 0;
}

Common Use Cases

Safe Division

#include <stdio.h>
int main() {
    int a = 20, b = 0;
    
    // Avoid division by zero
    float result = (b != 0) ? (float)a / b : 0;
    printf("Result: %.2f\n", result);
    
    return 0;
}

Array Bounds Checking

#include <stdio.h>
int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int size = 5;
    int index = 3;
    
    int value = (index >= 0 && index < size) ? arr[index] : -1;
    printf("Value at index %d: %d\n", index, value);
    
    return 0;
}

Advantages and Disadvantages

Advantages

  • Concise: Reduces code length for simple conditions
  • Readable: Clear for simple true/false assignments
  • Efficient: Can be optimized by compiler
  • Functional: Can be used in expressions

Disadvantages

  • Complexity: Can become hard to read when nested
  • Limited: Only suitable for simple conditions
  • Type Issues: Both values must be compatible types

Common Mistakes

Type Mismatch

// Problem: Different types in ternary
int x = 10;
// This may cause issues due to type mismatch
// char* result = (x > 5) ? "big" : 0;  // string vs int

// Solution: Use compatible types
char* result = (x > 5) ? "big" : "small";

Complex Nesting

// Difficult to read
int result = (a > b) ? (c > d) ? (e > f) ? 1 : 2 : 3 : 4;

// Better: Use if-else for complex logic
int result;
if (a > b) {
    if (c > d) {
        result = (e > f) ? 1 : 2;
    } else {
        result = 3;
    }
} else {
    result = 4;
}

Best Practices

  1. Use for Simple Conditions: Keep it simple and readable
  2. Avoid Deep Nesting: More than 2 levels becomes hard to read
  3. Use Parentheses: Make precedence clear
  4. Consider Alternatives: If-else might be clearer for complex logic

Summary

The ternary operator provides a concise way to write simple conditional expressions in C. Its syntax condition ? value_if_true : value_if_false makes code more compact for basic if-else scenarios. While powerful for simple conditions, it should be used judiciously to maintain code readability. For complex logic with multiple conditions, traditional if-else statements are often more appropriate and easier to understand.


Part of BCA Programming with C Course (UGCOA22J201)