Summary: in this tutorial, you’ll learn how to use the C ternary operator to make the code more concise.
Introduction to the C ternary operator #
The ternary operator is shorthand for an if...else and return statements. The ternary operator has the following syntax:
expression ? value_if_true : value_if_falseCode language: C++ (cpp)In this syntax, the ternary operator evaluates the expression first. If the result is true (not zero), the ternary operator returns value_if_true. Otherwise, the ternary operator returns the value_if_false.
The ternary operator is equivalent to the following:
if(codition)
return value_if_true;
else
return value_if_false;Code language: C++ (cpp)C Ternary operator examples #
Let’s take some examples of using the ternary operator.
1) A simple C ternary operator example #
The following example uses an if..else statement to display a string true or false based on the value of the is_active variable:
#include <stdio.h>
#include <stdbool.h>
int main()
{
bool is_active = true;
if (is_active)
{
printf("true");
}
else
{
printf("false");
}
return 0;
}Code language: C++ (cpp)The code is quite verbose. To make it more concise, you can use the ternary operator as follows:
#include <stdio.h>
#include <stdbool.h>
int main()
{
bool is_active = true;
printf( is_active ? "true" : false);
return 0;
}Code language: C++ (cpp)The five lines of code that use an if...else statement are replaced by one line of code that uses the ternary operator (:?).
2) Using the ternary operator example #
The following program uses an if...else statement to determine the discount on tickets based on age:
#include <stdio.h>
int main()
{
int age = 10; // age
float ticket_price = 100, // ticket price
discount; // discount
// determine the discount based on age
if (age < 5)
{
discount = 0.5;
}
else
{
discount = 0.15;
}
// get the ticket price
ticket_price = ticket_price * (1 - discount);
printf("Ticket price is %f\n", ticket_price);
return 0;
}
Code language: C++ (cpp)In this example, if the age is less than 5, the discount is 50%. Otherwise, the discount is 15%.
The following example is the same as above but uses the ternary operator instead:
#include <stdio.h>
int main()
{
int age = 10; // age
float ticket_price = 100; // ticket price
float discount = age < 5 ? 0.5 : 0.15;
// get the ticket price
ticket_price = ticket_price * (1 - discount);
printf("Ticket price is %f\n", ticket_price);
return 0;
}Code language: C++ (cpp)Summary #
- C ternary operator is
expression ? value_if_true : value_if_false. - Use the ternary operator to make the code more concise.