VOOZH about

URL: https://www.geeksforgeeks.org/dsa/implementing-ternary-operator-without-conditional-statement/

⇱ Implementing ternary operator without any conditional statement - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Implementing ternary operator without any conditional statement

Last Updated : 16 Jun, 2022

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.
 


Output
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.

  • For a= 1, the expression arr[a] reduces to arr[1] = b.
  • For a= 0, the expression arr[a] reduces to arr[0] = c.
     

Output
20
10


Asked In : Nvidia 
 

Comment
Article Tags: