In C language, the conditional operator is also known as the ternary operator because it operates on three operands. It is a shorthand way of expressing a simple if-else
condition. The syntax is compact, making it useful for situations where a quick decision needs to be made.
condition ? expression_if_true : expression_if_false;
condition
: An expression that evaluates to true
(non-zero) or false
(zero).expression_if_true
: This expression is executed if the condition is true
.expression_if_false
: This expression is executed if the condition is false
.#include <stdio.h>
int main() {
int a = 10, b = 20;
// Use the ternary operator to determine the maximum value
int max = (a > b) ? a : b;
printf("The maximum value is: %d\n", max);
return 0;
}
In this example:
(a > b)
is checked.a
is greater than b
, max
is assigned the value of a
.max
is assigned the value of b
.a
(10) is not greater than b
(20), max
is assigned b
, which is 20
.int result = (condition) ? value_if_true : value_if_false;
condition
is evaluated.condition
is true (non-zero), result
is assigned the value of value_if_true
.condition
is false (zero), result
is assigned the value of value_if_false
.#include <stdio.h>
int main() {
int number = 7;
// Determine if the number is even or odd
char *result = (number % 2 == 0) ? "Even" : "Odd";
printf("The number is: %s\n", result);
return 0;
}
In this example:
(number % 2 == 0)
checks if the number is divisible by 2
.result
is assigned the string "Even"
.result
is assigned "Odd"
.7 % 2 != 0
, the output will be: "The number is: Odd"
.if-else
decision.However, it is better to avoid using the conditional operator in complex situations, as it may decrease the readability of the code compared to using a regular if-else
statement.
if-else
The ternary operator is functionally equivalent to a simple if-else
but with a more concise syntax. For example:
Using if-else
:
int a = 10, b = 20;
int max;
if (a > b) {
max = a;
} else {
max = b;
}
Using the Ternary Operator:
int a = 10, b = 20;
int max = (a > b) ? a : b;
The ternary operator helps to write such conditional assignments in a single line.
The ternary operator can be nested, but using it this way is often discouraged because it can make code difficult to understand. For example:
int a = 5, b = 10, c = 15;
int max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
Here, the value of max
depends on multiple conditions, making it harder to read compared to an equivalent if-else
chain.
condition ? expression_if_true : expression_if_false;
if-else
for better readability.The conditional operator is a powerful tool in C for simplifying expressions, and its shorthand nature helps in scenarios where concise code is more readable.
@aCodeTutorials All Rights Reserved
privacy policy | about