Use of ternary (:?) operator

❓ The Ternary (?:) Operator in C

Elegant shorthand for conditional logic

The ternary operator, also known as the conditional operator, is a shorthand way of writing an if-else statement in C.

It is used for making decisions based on a condition and provides a concise way to choose between two values.

📝 General Syntax

condition ? expression_if_true : expression_if_false;

🔍 Condition

The expression that evaluates to true or false. This determines which value will be chosen.

✅ Expression if True

The value or expression returned when the condition is true (comes after the ?).

❌ Expression if False

The value or expression returned when the condition is false (comes after the :).

💡 Practical Example

#include <stdio.h>
int main() {
    int num = 10;
    char* result;

    // Using the ternary operator to assign a value to result based on the condition
    result = (num % 2 == 0) ? "Even" : "Odd";

    // Display the result
    printf("The number %d is %s.\n", num, result);

    return 0;
}

📤 Output:

The number 10 is Even.

🔍 Step-by-Step Breakdown

Condition: (num % 2 == 0) checks if num is even by testing if the remainder when divided by 2 equals 0.

If True: If num is even (num % 2 == 0 is true), then the value assigned to result is "Even".

If False: If num is odd, the value assigned is "Odd".

Output: The result is then printed using printf, displaying whether the number is even or odd.

⚖️ Ternary vs If-Else Comparison

✅ Using Ternary Operator

result = (num % 2 == 0) ? "Even" : "Odd";

Concise and readable for simple conditions

📝 Using If-Else

if (num % 2 == 0) {
    result = "Even";
} else {
    result = "Odd";
}

More verbose but explicit

🌟

Advantages of Ternary Operator

Concise: Reduces multiple lines to a single expression
Readable: Perfect for simple conditional assignments
🎯 Efficient: Can be used directly in expressions and function calls

🎯 Key Takeaways

💡 Ternary operator is perfect for simple conditional assignments
📝 Use if-else for complex logic with multiple statements
⚖️ Choose based on readability and complexity of your condition

Post a Comment

0 Comments