-1
bool x = someFuncThatReturnsTrueorFalse();
if (!x && (str1.length() != str2.length()) {
    // do nothing
} else {
    // do something
}

How would I rearrange the code above to eliminate the else statement? I need to do nothing if bool = false and str1 and str2 have different lengths. Otherwise, I need to do something (e.g. function call).

For the life of me, I can't think of any way to change this. Let me know if you need further details.

user3354230
  • 15
  • 1
  • 7
  • Trivial boolean algebra. The opposite of `if (A && B)` is `if (!(A && B))` which is equivalent to `if ((!A) || (!B))`. – Peter Sep 22 '20 at 00:58

2 Answers2

1

The simplest way is putting !() around the condition.

bool x = someFuncThatReturnsTrueorFalse();
if (!(!x && (str1.length() != str2.length())) {
    // do something
}

Another way is using De Morgan's laws: !(A && B) is equivalent to !A || !B.

bool x = someFuncThatReturnsTrueorFalse();
if (x || (str1.length() == str2.length()) {
    // do something
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

There is nothing wrong leaving as is. The code will still compile

Angus
  • 51
  • 6