The ternary operator, also known as the conditional operators in the C language can be used for statements of the form if-then-else.
The basic syntax for using ternary operator is:
(Expression1)? Expression2 : Expression3;
Here is how it works:
- The question mark
?
in the syntax represents the if part. - The first expression (expression 1) returns either true or false, based on which it is decided whether (expression 2) will be executed or (expression 3)
- If (expression 1) returns true then the (expression 2) is executed.
- If (expression 1) returns false then the expression on the right side of
:
i.e (expression 3) is executed.
Example: Using Ternary Operator
Here is a code example to show how to use ternary operator.
#include <stdio.h>
int main() {
int a = 20, b = 20, result;
/* Using ternary operator
- If a == b then store a+b in result
- otherwise store a-b in result
*/
result = (a==b)?(a+b):(a-b);
printf("result = %d",result);
return 0;
}
Output
result = 40