C Ternary Operator

The ternary operator is a shorthand operator in C programming language that allows us to write concise code for simple conditional statements. The ternary operator is also called the conditional operator and has the following syntax:


 

Syntax :

(condition) ? expression1 : expression2;

Here, the condition is evaluated, and if it is true, the expression expression1 is executed. If the condition is false, the expression expression2 is executed.

Here's an example of the ternary operator in C programming language:

#include <stdio.h>

int main() {
    int num = 10;
    (num > 0) ? printf("The number is positive\n") : printf("The number is negative\n");
    return 0;
}

In the above example, we have used the ternary operator to check if num is positive or negative and print the appropriate message. If num is greater than 0, the expression printf("The number is positive\n") is executed, otherwise, the expression printf("The number is negative\n") is executed.

Note that the ternary operator should be used only for simple conditional statements. If the condition or expressions are complex, it is better to use the if-else statement for better readability and maintainability of the code.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

68820