Ideal If the operator structure for two logical values

I was not sure what to look for - but I was looking for an elegant way, if possible, to structure an if statement that uses two Boolean values ​​that can easily print all four possibilities.

Variables

bool a = true;
bool b = true;

I was not sure if there was a best practice in terms of checking both negativity and continuation, etc.

A very hasty written example:

if(!a && !b)
{
   //Output (-,-)
}
else
{
   if(a || b)
   {
       if(a)
       {
           //Output (+,-)
       }
       else
       {
           //Output (-,+)
       }
   }
   else
   {
       //Output (+,+)
   }
}

Sorry for all the gullwings ({}) I'm a bit of a formatting junkie. Anyway - thanks for any suggestions!

+3
source share
7 answers

It depends on how you define elegant.

So I'm going to go with my own definition:

  • Symmetrical.
  • readable.
  • Avoid unnecessary complexity.

:

if( a ) {
  if( b ) {
     ...
  } else {
     ...
  }
} else {
  if( b ) {
     ...
  } else {
     ...
  }
}

, , , , , .

, , . , :

  • () , , , .
  • , . , .
  • , 4 , switch/case.
+3

, , ... , if ?

, :

if (a && b)
    // Output (+, +)
else if (!a && b)
    // Output (-, +)
else if (a && !b)
    // Output (+, -)
else
    // Output (-, -)

, , , .

+3

if ...

case a, b of
  true, true => "+,+"
| false, true => "-,+"
| true, false => "+,-"
| false, false => "-,-"

C C, C

switch (((!!a) * 2) + (!!b))
{
  case 3: \\ "+,+"
    break;
  case 2: \\ "+,-"
    break;
  case 1: \\ "-,+"
    break;
  case 0: \\ "-,-"
    break;
}
+2

.

Output(strings[(a ? 2 : 0) + (b ? 1 : 0)])
0

:

result = (name & id) ? "(+,+)" : 
         (!name & !id) ? "(-,-)" : 
         (name & !id) ? "(+,-)" : "(-,+)";

- , , , ( ).

0

, :

char table[2] = {'-','+'};
printf("(name%c,id%c)",table[!!name],table[!!id]);

!

0

@templatetypedef. , , @biziclop

    if (a && b) {
      // Output (+, +)
    } else if (a) {
      // Output (+, -)
    } else if (b) {
      // Output (-, +)    
    } else {
      // Output (-, -)
    }

, ,

if (a && b && c)  {

} else if (a && b) {

} else if (a && c) {

} else if (b && c) {

} else if (a) {

} else if (b) {

} else if (c) {

} else {

}
0

All Articles