2014-08-31 75 views
0

我遇到了一個行爲,我沒有期望在無符號整數上使用按位運算。我會切入我的榜樣。無符號int零位表示

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); 

上面的代碼產生以下輸出:

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

的最後一行是什麼讓我困惑。不應a & b == a評估爲true,因爲a & b == (unsigned int)0a == (unsigned int)0

+5

http://en.cppreference.com/w/cpp/language/operator_precedence – 2014-08-31 06:47:42

+0

[C++按位操作]的可能重複(http://stackoverflow.com/questions/14645473/c-bitwise-operations) – user2357112 2014-08-31 06:48:44

回答

7

你會得到這種行爲,因爲你沒有意識到==&之前C operator precedence table。事實上,一個好的編譯器會警告你,立刻對您的代碼:

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); 
           ^
           ( ) 

確保您的警告被打開,像g++ -Wall -Wextra -Werror

5

你應該寫:

(a & b) == a 

現在你會得到1因爲a & bwill be evaluated first

(a & b) = 00 == 0爲1

在你的情況,a & b == a被評爲a & (b == a)b == a是1並且a & 1是0.