Search code examples
c++logic

How to simplify this logical expression in a single return statement?


I have been trying to simplify this function in a single return A ... B ... C statement but some cases always slip out. How could this checks be expressed in a logical way (with and, or, not, etc.)?

bool f(bool C, bool B, bool A)
{
if (A)
    return true;

if (B)
    return false;
   
if (C)
    return true;

return false;
}

Solution

  • bool f(bool C, bool B, bool A)
    {
    if (A)
        return true;
    
    if (B)
        return false;
       
    if (C)
        return true;
    
    return false;
    }
    

    is equivalent to

    bool f(bool C, bool B, bool A)
    {
    if (A)
        return true;
    else if (B)
        return false;
    else if (C)
        return true;
    else 
        return false;
    }
    

    is equivalent to:

    bool f(bool C, bool B, bool A)
    {
    if (A)
        return true;
    else if (!B)
    {
        if (C)
            return true;
        else
            return false;
    }
    else
        return false;
    }
    

    is equivalent to:

    bool f(bool C, bool B, bool A)
    {
    if (A)
        return true;
    else if (!B and C)
        return true;
    else
        return false;
    }
    

    is equivalent to:

    bool f(bool C, bool B, bool A)
    {
    if (A or (!B and C))
        return true;
    else
        return false;
    }
    

    is equivalent to:

    bool f(bool C, bool B, bool A)
    {
    return (A or (!B and C));
    }