How do I do this with the ternary operator on the same line?

Consider this const declaration for int num

:

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

      

I want to const int num

follow this truth table (from which I am sorry, was edited from my original question to reflect the pattern in my program):

              b
  a      true   false
true      2      4
false     4      2

      

How do I modify the above declaration const int num

to achieve this using the ternary operator? I know how to declare such num

as const using a lambda function and nested if statements or switch statenents inside a lambda function, but I just wanted to know how to do it using a ternary operator. As a bonus, what if you need to use 3 or more of these bool values ​​(no specific pattern in the truth table)?

+3


source to share


4 answers


You can write a declaration like

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

      

At least it's clearer than

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

      



Here is a demo 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;
}

      

Program output

2
4
4
2

      

+3


source


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

      

EDIT:

As a bonus, what if you need to use 3 or more of these bool values?

I wouldn't use this syntax at all. I would declare the table as



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

      

and now it's simple:
 int res = truthTable[!true][!false]..[!true]

!true

becomes 0

, !false

becomes 1

, then the correct value will be pulled from the array.

+6


source


David Haim's answer is great for a lot of other values ​​in the truth table. However, in this particular case, there is an easily identifiable mathematical relationship that we can use:

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

      

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


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

              b
  a      true   false
true      2      3
false     4      5

      


Given this truth table:

b true false true 2 4 false 4 2

Another way to return the correct values ​​for this:

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

      

It's not really some kind of math. It simply means that when a

and are the b

same, we want 2

, but when a

and b

are different, we want 4

. This truth table is exactly the same as the operator truth table ==

, we just return 2

/ 4

instead of true

/ false

.

+6


source


In this particular case, I would go:

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

      

+1


source







All Articles