This post will implement a 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.

If x = 1, a is returned; 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.

The following C program demonstrates it:

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 return the value present at index 0 or 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.

This is demonstrated below in C. 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 only evaluated if x is false. We can apply this logic to solve this problem. Consider the following code snippet:

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

Initially, we check whether x is 1 or 0. If x = 1, the result is set to a and result = b subexpression won’t get 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.

 
This approach is demonstrated below in C:

Download  Run Code

Output:

20
10