Ternary operator in C language

The ternary operator in C is a shorthand way of writing an if-else statement. It has the form: condition ? true_expression : false_expression. If the condition is true, the ternary operator evaluates to the value of true_expression, otherwise, it evaluates to the value of false_expression.

Syntax of ternary operator

variable = (condition) ? expression1 : expression2;

In this syntax, variable is the variable that will be assigned a value based on the condition, condition is the Boolean expression being evaluated, expression1 is the value that variable will be assigned if condition is true, and expression2 is the value that variable will be assigned if condition is false.

Example:

#include <stdio.h>

int main() {
   int num;
   printf("Enter a number: ");
   scanf("%d", &num);
   
   (num % 2 == 0) ? printf("%d is even.\n", num) : printf("%d is odd.\n", num);
   
   return 0;
}

Output:

Enter a number 5
5 is odd.

Enter a number 10
10 is even.

In this example, the ternary operator is used to determine the maximum value between num1 and num2. The condition num1 > num2 is checked, and if it evaluates to true, the value of num1 is assigned to max. If it evaluates to false, the value of num2 is assigned to max. The result is then printed to the console.

Another example of ternary operator:

#include <stdio.h>

int main() {
   int num1 = 5;
   int num2 = 10;
   int max;

   max = (num1 > num2) ? num1 : num2;

   printf("The maximum value is %d\n", max);

   return 0;
}

Output:

The maximum value is 10

Here, the ternary operator is used to compare the values of num1 and num2. If num1 is greater than num2, then num1 is assigned to max, otherwise, num2 is assigned to max. In this case, since num2 is greater than num1, the value of max is assigned to 10. Finally, the value of max is printed using the printf() function.