Conditional Expression in C programming

Using the Conditional Expression in C

Conditional Expression in C

The conditional expression, also known as the ternary operator, is a concise way to perform conditional assignments in C. It allows you to assign a value to a variable based on a condition, all within a single line of code.

Purpose

The conditional expression is useful for:

  • Performing simple conditional assignments in a compact format.
  • Making code more readable by avoiding multiple lines of if-else statements.
  • Improving code efficiency and reducing verbosity.

Syntax

The syntax for the conditional expression is as follows:

condition ? expression1 : expression2

In this syntax:

  • condition is the expression that is evaluated as either true or false.
  • If condition is true, expression1 is evaluated and its value is returned.
  • If condition is false, expression2 is evaluated and its value is returned.

Examples

1. Basic Usage

Here’s a simple example demonstrating the use of the conditional expression:

#include <stdio.h>

int main() {
    int age = 20;

    // Using conditional expression to assign a value based on age
    const char* status = (age >= 18) ? "Adult" : "Minor";

    printf("Status: %s\n", status);  // Output: Status: Adult

    return 0;
}

In this example, the conditional expression checks if age is greater than or equal to 18. If true, it assigns "Adult" to status; otherwise, it assigns "Minor".

2. Nested Conditional Expression

You can also nest conditional expressions for more complex conditions:

#include <stdio.h>

int main() {
    int score = 85;

    // Using nested conditional expressions to determine grade
    char* grade = (score >= 90) ? "A" :
                  (score >= 80) ? "B" :
                  (score >= 70) ? "C" : "D";

    printf("Grade: %s\n", grade);  // Output: Grade: B

    return 0;
}

In this example, nested conditional expressions are used to determine the grade based on the score.

Note: While the conditional expression is concise, it can sometimes reduce code readability if overused or nested deeply. For complex conditions, consider using traditional if-else statements.

Comments

Popular Posts