Skip to main content

Ternary Operator in C

The ternary operator (?:)

The ternary operator (also known as the conditional operator) in C is a shorthand way to write an if-else statement.

It is written as

"condition ? true_result : false_result"

Where,

  • "condition" is an expression that evaluates to either true or false
  • "true_result" is the value or expression that will be returned if the condition is true
  • "false_result" is the value or expression that will be returned if the condition is false

For example:

int x = 5, y = 10;
int max = (x > y) ? x : y;

In this case, the expression "x > y" evaluates to false, so the value of "y" is assigned to the variable "max".

Using Ternary Operator, instead of if-else

As suggested above, ternary operator in C is a shorthand way to write an if-else statement.

Here is a simple program that uses an if-else statement to determine if a number is positive or negative:

#include <stdio.h>

int main() {
int x;
printf("Enter a number: ");
scanf("%d", &x);
if (x > 0) {
printf("%d is positive\n", x);
} else {
printf("%d is non-positive\n", x);
}
return 0;
}
Output:

Here is the equivalent program that uses the ternary operator:

#include <stdio.h>

int main() {
int x;
printf("Enter a number: ");
scanf("%d", &x);
printf("%d is %s\n", x, x > 0 ? "positive" : "non-positive");
return 0;
}
Output:
note

Both the program will give the same output and will check whether the entered number is positive or not.

When Should You not use Ternary Operator

  • The ternary operator is useful for simple cases where the logic can be expressed in a single line of code.
  • However, it can make code more difficult to read and understand when used for complex logic or nested statements.
  • Therefore, it is generally recommended to use the ternary operator only when the logic is simple and the intent of the code is clear.

For Example:

In order to find the grade of a student based on their score, instead of

printf("The student's grade is %c.\n", 
score >= 90 ? 'A' :
(score >= 80 ? 'B' :
(score >= 70 ? 'C' :
(score >= 60 ? 'D' : 'F'))));

One should use if-else block, as below:

if (score >= 90) {
printf("The student's grade is A.\n");
} else if (score >= 80) {
printf("The student's grade is B.\n");
} else if (score >= 70) {
printf("The student's grade is C.\n");
} else if (score >= 60) {
printf("The student's grade is D.\n");
} else {
printf("The student's grade is F.\n");
}

Explanation If the expression is too complex or if the ternary operator is nested multiple times, it is better to use if-else statement.