![]() |
VOOZH | about |
How to implement ternary operator in C++ without using conditional statements.
In the following condition: a ? b: c
If a is true, b will be executed.
Otherwise, c will be executed.
We can assume a, b and c as values.
1. Using Binary Operator
We can code the equation as :
Result = (!!a)*b + (!a)*c
In above equation, if a is true, the result will be b.
Otherwise, the result will be c.
10 20
2. Using Array
int arr[] = { b, a };
We can return the value present at index 0 or 1 depending upon the value of a.
20 10
Asked In : Nvidia