Ternary operator in C
The ternary operator evaluates a condition and chooses one of two values based on whether that condition is true or false. It is written as condition ? true_value : false_value.
Here is a simple C script to illustrate that point:
#include <stdio.h>
// To compile this program, you can use the following command:
// gcc -o ternary_example ternary_example.c
int main() {
// Define a simple variable to test
int age = 20;
// The ternary operator checks if age is 18 or older.
// If (age >= 18) is true, it assigns "Adult" to the status pointer.
// If (age >= 18) is false, it assigns "Minor".
const char* status = (age >= 18) ? "Adult" : "Minor";
// Print out the resulting status
printf("Since the age is %d, the person is an %s.\n", age, status);
return 0;
}
This approach replaces four lines of traditional if-else branching with a single, highly readable line of logic.