Search code examples
visual-c++code-analysisvisual-studio-2022

Why is code analysis warning "Using logical && when bitwise & was probably intended" being raised?


Code:

BOOL CCreateReportDlg::CanSwapBrothers()
{
    BOOL            b1in2 = FALSE, b2in1 = FALSE;
    CStringArray    aryStrNames;

    // Must have valid data
    if (!IsSwapBrotherInit())
        return FALSE;

    // Get cell pointers
    auto pCell1 = GetSwapBrotherCell(1);
    auto pCell2 = GetSwapBrotherCell(2);
    if (pCell1 != nullptr && pCell2 != nullptr)
    {
        // Look for brother (cell 1) in cell 2 array
        auto strName = pCell1->GetText();
        pCell2->GetOptions(aryStrNames);
        const auto iNumNames = aryStrNames.GetSize();
        for (auto iName = 0; iName < iNumNames; iName++)
        {
            if (aryStrNames[iName] == strName)
            {
                b1in2 = TRUE;
                break;
            }
        }

        if (b1in2)
        {
            // Look for brother (cell 2) in cell 1 array
            auto strName = pCell2->GetText();
            pCell1->GetOptions(aryStrNames);
            const auto iNumNames = aryStrNames.GetSize();
            for (auto iName = 0; iName < iNumNames; iName++)
            {
                if (aryStrNames[iName] == strName)
                {
                    b2in1 = TRUE;
                    break;
                }
            }
        }
    }

    return b1in2 && b2in1;
}

The line of interest is the return statement:

return b1in2 && b2in1;

I am getting a code analysis warning:

lnt-logical-bitwise-mismatch Using logical && when bitwise & was probably intended.

As far as I am concerned my code is correct. Why is this being raised?


Solution

  • The compiler sees && applies to integer operands and an implicit conversion of the result to an integer type. BOOL has multiple bits; it isn't the same as the built-in type bool.

    As noted in the page you linked to, "A logical operator was used with integer values" will cause this warning and that condition is certainly present here.

    "MFC" coding styles violate modern recommendations in a lot of ways, using a non-standard boolean type is just one of the smaller issues. CStringArray is also a code smell, modern C++ uses templated containers and has powerful algorithms for manipulating them, you never should be writing search code yourself.