Sometimes we will want to set the value of a variable based on if a condition is fulfilled. In the example below, the value of the variable is_adult is set to 1 if the person is at least 18 otherwise it must be set to 0:
#include <stdio.h>
int main(void) {
int age;
printf("Please enter your age: ");
scanf("%d", &age);
int is_adult;
if (age >= 18) {
is_adult = 1;
} else {
is_adult = 0;
}
printf("Is adult: %d\n", is_adult);
return 0;
}
without-ternary.c Copy
This can be condensed using the ternary operator. The basic format is:
datatype variable = condition?value_when_true:value_when_false;
Our code above can be refactored to give:
#include <stdio.h>
int main(void) {
int age;
printf("Please enter your age: ");
scanf("%d", &age);
int is_adult = (age >= 18) ? 1 : 0;
printf("Is adult: %d\n", is_adult);
return 0;
}
with-ternary.c Copy
Happy coding!