Implement Ternary Operator Without Using Conditional Expressions

In this post, we will see how to implement ternary-like operator in C without using conditional expressions like ternary operator, if–else expression or switch-case statements.


 

The solution should implement the condition x ? a : b where if x = 1, ‘a’ is returned, else if x = 0, ‘b’ should be returned.

 

1. Develop custom expression

The idea is to use the expression x * a + !x * b or x * a + (1 - x) * b.

 

How this works?

Let’s consider the first expression x * a + !x * b:

– For x = 1, the expression reduces to (1 * a) + (!1 * b) = a
– For x = 0, the expression reduces to (0 * a) + (!0 * b) = b

 

Download   Run Code

Output:

20
10

 

2. Using array

Another plausible way is to construct an array of size 2 in such a manner that index 0 of the array holds the value of ‘b’ and index 1 holds the value of ‘a’ as shown below:

int arr[] = { b, a };

Then we can simply return the value present at index 0 or at index 1 depending upon the value of ‘x’.

– For x = 1, the expression arr[x] reduces to arr[1] = a
– For x = 0, the expression arr[x] reduces to arr[0] = b

 
Please note that this approach doesn’t use any operators in C, such as arithmetic, relational, logical, conditional, etc.

 

Download   Run Code

Output:

20
10

 

3. Using Short Circuiting

Another approach is to use short-circuiting in boolean expressions. For AND operations in C such as x && y, y is evaluated only if x is true. Similarly, for OR operation like x || y, y is evaluated only if x is false. We can apply this logic to solve this problem. Consider below code snippet –

x && ((result = a) || !a) || (result = b)

Initially we check whether x is 1 or 0. If x = 1, the result would be set to ‘a’ and (result = b) subexpression won’t be executed. If x = 0, the ((result = a) || !a) subexpression won’t be executed and the result is set to ‘b’. Please note that !a is added to handle the case when a = 0.

 

Download   Run Code

Output:

20
10

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of