Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Sunday, 2 June 2019

Implementing ternary operator without any conditional statement


How to implement a 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.


We can code the equation as :
Result = (!!a)*b + (!a)*c
In above equation, is a is true, result will be b.
Otherwise, the result will be c.


// C code to implement ternary operator
#include<stdio.h>

// Function to implement ternary operator without
// conditional statements
int ternaryOperator(int a, int b, int c)
{
    // If a is true, we return (1 * b) + (!1 * c) i.e. b
    // If a is false, we return (!1 * b) + (1 * c) i.e. c
    return ((!!a) * b + (!a) * c);
}

// Driver code
int main()
{
    int a = 0, b = 10, c = 20;

    // Function call to output b or c depending on a
    printf("%d",ternaryOperator(a, b, c));

    return 0;
}

Output:
20

0 comments:

Post a Comment