mardi 8 octobre 2019

Why bitwise OR and AND logic is not working as expected?

I have the below sample code. I was always under the impression that doing Bitwise OR on enum values, will allow me to check the result (using Bitwise AND) to see which enum values are included in the result and which are not.

For example, if I do result = mouse | headphone, then I can check agaist result & mouse == mouse as condition to know if mouse is included in result or not. But it seem that whatever I & result with, say X, I always end up with X. Why?

In the below code, I thought that the if should fail since straw was not included in options, but it does not..

#include <iostream>
#include <iomanip>

using namespace std;

enum lStock  
{
    milk,
    choclate,
    tv,
    cable,
    mouse,
    fan,
    headphone,
    cup,
    straw,
    pen,
    candy,
    glasses,
    book,
    plug

};


int main()
{
    lStock loptions = static_cast<lStock>(  static_cast<int>(mouse) | static_cast<int>(headphone)
                                            | static_cast<int>(cup) | static_cast<int>(pen)     );

    if ((static_cast<int>(loptions)) & (static_cast<int>(straw)) == static_cast<int>(straw))
    {
        cout << "bring straw!" << endl;
    }

    system("PAUSE");
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire