Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If condition A is matched, condition B needs to be matched in order to do action C

Your first step in these kinds of problems is always to make a logic table.

A | B | Result
-------------------
T | T | do action C
T | F | ...
F | T | do action C
F | F | do action C

Once you've made the table, the solution is clear.

if (A && !B) {
  ...
}
else {
  do action C
}

Do note that this logic, while shorter, may be difficult for future programmers to maintain.


You have two options:

  1. Write a function that performs "action C".

  2. Rearrange your logic so that you do not have so many nested if statements. Ask yourself what conditions cause "action C" to occur. It looks to me like it happens when either "condition B" is true or "condition A" is false. We can write this as "NOT A OR B". Translating this into C code, we get

    if (!A || B) {
        action C
    } else {
        ...
    }
    

To learn more about these kind of expressions, I suggest googling "boolean algebra", "predicate logic", and "predicate calculus". These are deep mathematical topics. You don't need to learn it all, just the basics.

You should also learn about "short circuit evaluation". Because of this, the order of the expressions is important to exactly duplicate your original logic. While B || !A is logically equivalent, using this as the condition will execute "action C" when B is true regardless of the value of A.


You can simplify the statement like this:

if ((A && B) || (!A)) // or simplified to (!A || B) as suggested in comments
{
    do C
}

Otherwise put code for 'C' in a separate function and call it:

DoActionC()
{
    ....
    // code for Action C
}
if (condition A)
{
    if(condition B)
    {
        DoActionC(); // call the function
    }
    else
    ...
}
else
{
   DoActionC(); // call the function
}

In a language with pattern matching, you can express the solution in a way that more directly reflects the truth-table in QuestionC's answer.

match (a,b) with
| (true,false) -> ...
| _ -> action c

If you're not familiar with the syntax, each pattern is represented by a | followed by the values to match with (a,b), and the underscore is used as a wildcard to mean "any other values". Since the only case where we want to do something other than action c is when a is true and b is false, we explicitly state those values as the first pattern (true,false) and then do whatever should be done in that case. In all other cases, we fall through to the "wildcard" pattern and do action c.