Ternary operator in C language
The ternary operator is a conditional operator that allows to write conditional and default option in single statement. This method is an alternative for using if-else and nested if-else statements. The order of execution for this operator is from left to right.
Syntax
 1 <condition> ? <statement1> : <statement2>
1. condition : any condition which returns boolean value2. statement1: If condition true, statement 1 will execute3. statement2: if condition false, statement 2 will execute
minimum using ternary operator
 1 #include <stdio.h>
 2 
 3 int main() {
 4     
 5     int a = 10, b = 5;
 6     int res;
 7     
 8     // check and assign minimum number
 9     res = a < b ? a : b;
 10     printf("A minimum number is : %d", res);
 11     
 12     return 0;  
 13 }
In the above example, a variables are declared and initialized with values. A ternary operator validates the specified expression and evaluates respective blocks based on the expression result. It returns the variable value that assigned to the variable. The resulting value will be the minimum value and printed using printf() function.
Output
 1 A minimum number is : 5

Nested ternary operator

Ternary operator
 1 #include <stdio.h>
 2 
 3 int main() {
 4 
 5     int a = 10, b = 5, c = 20, res;
 6     
 7     res = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
 8     printf("The result value is : %d", res);
 9     
 10     return 0;
 11 }
In the above example, a variables are declared and initialized with value. A ternary operator validates the value using specified expression and based on result, it validates maximum value using nested ternary operator and finds the maximum value. A result will be assigned to the variable and printed using printf() function.
Output
 1 The result value is : 20

ternary operator with function

ternary operator with function
 1 #include <stdio.h>
 2 
 3 int main() {
 4     
 5     int a = 10, b = 5;
 6     int res;
 7     
 8     res = a < b ? printf("Hello world") : printf("World");
 9     printf("\nA result is : %d", res);
 10     
 11     return 0;  
 12 }
In the above example, a variables are declared and intialized that validated using ternary operator by specifying an expression. As value of variable a is greater than b, it executes ternary operator else block that prints specified string on console. A printf() function returns a number that printed on console. As it prints 5 characters on console, it returns 5 that assigned to the variable. A result is printed on console.
Output
 1 World
 2 A result is : 5
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us