2014-08-31 7 views
0

부호없는 int에 대해 비트 연산을 사용하지 않을 것으로 예상되는 동작이 발생했습니다. 나는 나의 모범을 바로 잡을 것이다.부호없는 int 0 비트 표현

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 == (unsigned int)0a == (unsigned int)0이므로 a & b == atrue으로 표시해야합니까?

+5

http://en.cppreference.com/w/cpp/language/operator_precedence –

+0

[C++ bitwise operations] 가능한 중복 (http://stackoverflow.com/questions/14645473/c-bitwise-operations) – user2357112

답변

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 will be evaluated firsta & b 때문에 얻을 것이다 :

(a & b) = 0, 0 == 0 귀하의 경우 1.

입니다 a & b == ab == aa & (b == a)으로 평가 1이고, a & 1은 0이다.

5

=='s precedence over &으로 인해 a & b == aa & (b == a) (예상 한 것처럼 (a & b) == a이 아님)으로 평가됩니다.