How to do this with the ternary operator in one line?

187 views Asked by At

Consider this const declaration of int num:

int main() {
    bool a = true, b = false;
    // ...
    const int num = a ? (b? 2 : 4) : 4;
    std::cout << num;
}

What I want is for const int num to follow this truth table (which I apologize has been edited from my original question to reflect the pattern in my program):

              b
  a      true   false
true      2      4
false     4      2

How to modify the above const int num declaration to achieve this using the ternary operator? I know how to declare such num to be const using a lambda function and nested if-statements or switch statenents within the lambda function, but I just wanted to know how to do it using the ternary operator. As a bonus, what if 3 or more such bool values were to be used (with no specific pattern in the truth table)?

4

There are 4 answers

0
Vlad from Moscow On BEST ANSWER

You can write the declaration like

const int num = ( a ^ b ) ? 4 : 2;

At least it is more clear than

const int num = a ? (b? 2 : 4) : 4;

Here is a demonstrative program

#include <iostream>

int main()
{
    std::cout << ( false ^ false ? 4 : 2 ) << std::endl;
    std::cout << ( true  ^ false ? 4 : 2 ) << std::endl;
    std::cout << ( false ^ true  ? 4 : 2 ) << std::endl;
    std::cout << ( true  ^ true  ? 4 : 2 ) << std::endl;
}

The program output is

2
4
4
2
6
David Haim On
const int num = a ? (b? 2 : 3) : (b? 4: 5);

EDIT:

As a bonus, what if 3 or more such bool values were to be used?

I wouldn't use such syntax at all. I would declare my table as

int truthTable[2][2]..[2] = {{..},...{..}}

and now simply:
int res = truthTable[!true][!false]..[!true]

!true will become 0 , !false will become 1, then, the right value will be pulled from the array.

1
nhgrif On

David Haim's answer is great for lots of other values in the truth table. In this specific instance however, there is an easily identifiable mathematical relationship we can make use of:

const int num = (a ? 2 : 4) + (b ? 0 : 1);

We may not always have such an easily identifiable relationship in the truth table though.


The above expression was based on the question's original truth table, which looked like this:

              b
  a      true   false
true      2      3
false     4      5

Given this truth table:

b a true false true 2 4 false 4 2

There's another way we can return the correct values for this one:

const int num (a == b) ? 2 : 4

This one isn't really any sort of math. It's just simply recognizing that when a and b are the same, we want 2, but when a and b are different, we want 4. This truth table is exactly the same as the truth table for the == operator, we're just returning 2/4 instead of true/false.

1
bolov On

Well in this particular case I would go for:

const int num = (a == b) ? 2 : 4;