Search code examples
c++bit-manipulationunsigned

bit representation of unsigned int zero


I ran into a behavior which I didn't expect using bitwise operations on unsigned ints. I'll cut right to my example.

unsigned int a = 0;
unsigned int b = 0;
std::printf("a & b: %u\n", a & b);
std::printf("a == b: %i\n", a == b);
std::printf("a & b == a: %i\n", a & b == a);

The above code produces the following output:

a & b: 0
a == b: 1
a & b == a: 0

The last line is what confuses me. Shouldn't a & b == a evaluate to true, since a & b == (unsigned int)0 and a == (unsigned int)0?


Solution

  • You're getting this behavior because you didn't realize == comes before & in the C operator precedence table. In fact, a good compiler will warn you straight away about your code:

    t.cpp:10:35: warning: & has lower precedence than ==; == will be evaluated first [-Wparentheses]
    std::printf("a & b == a: %i\n", a & b == a);
                                      ^~~~~~~~
    t.cpp:10:35: note: place parentheses around the '==' expression to silence this warning
    std::printf("a & b == a: %i\n", a & b == a);
                                      ^
                                        (     )
    t.cpp:10:35: note: place parentheses around the & expression to evaluate it first
    std::printf("a & b == a: %i\n", a & b == a);
                                      ^
                                    (    )
    

    Make sure your warnings are turned on, like g++ -Wall -Wextra -Werror.