Conditional Operator
Conditional operators are also called ternary operators as it takes three arguments. You can think of a conditional operator as short form of if then else block.
Syntax:
expression 1 ? expression 2 : expression 3
Here;
- Expression 1 must be a condition.
- Expression 2 and 3 are some statements.
If Expression 1 evaluates to be “true” (non-zero) then expression 2 will be executed, otherwise expression 3 will be executed.
Now, we can also write it as;
Condition ? Statement 1 : Statement 2
It is a single line implementation of if then else
Implementation:
As it’s a single line operation, and it act like a decision control structure. Hence, it can be used for assigning a value to a variable, depending upon some condition.
Let’s see the example code below;
The highlighted line of code is representing the value assignment to the variable, depending on the specified condition.
The first expression that is a condition: n1>n2
Second expression is a variable to be assigned to the variable “max” if the condition evaluates as “true”
Third expression is also a variable to be assigned to the variable “max” if the condition evaluates as “false”
Nested Conditional Operators:
Like if then else blocks, conditional operators can also be nested. There can be many forms as per the program’s requirement;
a ? b : c
This is the simplest form that corresponds to if then else block. We have already discussed this.
a ? b : c ? d : e ? f : g ? h : i
This form is a bit complex, it can be understood as if else if block;
Break the expression into smaller parts;
In terms of if else blocks;
a ? b ? c : d : e
Following is the expansion for this form of nested conditional operator;
In terms of if else blocks;