- The conditional expression can be used as shorthand for some if-else statements.
- Conditional operator is also called as ternary operator.
- This operator consist of two symbols: the question mark (?) and the colon (:).
The general syntax of the conditional operator is:
Identifier = (test expression)? Expression1: Expression2 ;
This is an expression, not a statement, so it represents a value. The operator works by evaluating test expression. If it is true (non-zero), it evaluates and returns expression1. Otherwise, it evaluates and returns expression2.
The classic example of the ternary operator is to return the smaller of two variables. Every once in a while, the following form is just what you needed. Instead of…
if (x < y)
min = x;
min = y;
You just say…
min = (x < y) ? x : y;
Suppose that x and y are integer variables whose values are 100 and 4, respectively. After executing above statement, the value of min is 4.
This is the only operator in C that makes use of three operands. It test condition corresponding to test expression, if it is true the value corresponding to Expression1 and it is false it corresponds to the value of Expression2.
int a, b, result, choice;
printf(“Enter first number \n”);
printf(”Enter second number\n”);
printf(“Enter 1 for addition or 2 for multiplication \n”);
result = (choice==1)?a+b:(choice==2)?a*b:printf(“Invalid Input”);
printf(“The result is %d\n\n”,result);
|Enter first number
Enter second number
Enter 1 for addition or 2 for multiplication
The result is 30