The conditional operator, also known as the ternary operator, is a shorthand way of writing simple conditional statements in the C programming language.
condition ? expression_if_true : expression_if_false;
Operator | Description |
---|---|
? | Conditional operator (Ternary operator) |
: | Separates the true and false expressions |
Here's an example of how the conditional operator can be used in C:
#include <stdio.h> int main() { int num = 10; char* message = (num > 5) ? "Greater than 5" : "Less than or equal to 5"; printf("The message is: %s\n", message); return 0; }
The message is: Greater than 5
In this example, the program determines whether the variable num
is greater than 5 and assigns an appropriate message to the message
variable using the conditional operator.