![](/img/trans.png)
[英]I can't understand why I get this result when I bitwise OR a short and char
[英]Bitwise AND: why do I get this behaviour?
我在這里有這個簡單的程序:
#include <iostream>
#include <bitset>
using namespace std;
int main() {
unsigned char a = 0b11100111;
if((a & (1<<2)) == true) // THIS IS THE LINE
cout << "Entering if block!" << endl;
else
cout << "Too bad, maybe next time.." << endl;
bitset<8> x(a & (1<<2));
cout << x << '\n';
}
你能告訴我為什么這個if((a & (1<<2)) == true)
輸出:太糟糕了,也許下次.. 00000100
而這個if((a & (1<<2))
輸出:輸入 if 塊!00000100
我正在使用 g++ -std=c++14 進行編譯。
0b100
是一個數字,不應與 true 進行比較。
嘗試將 if 語句更改為:
if (a & (1<<2))
或等效地
if((a & (1<<2)) != 0)
因為在if
語句中,任何不為零的都被認為是true
。
這體現了使用多余的== true
的陷阱,有些人喜歡為了清晰的目的而使用它:有時它會破壞代碼。
當(a & (1<<2)) == true
被評估時, true
( bool
類型)被隱式轉換為值為1
的int
類型,因此a
也被轉換為int
類型。
但是(a & (1<<2))
不是1
,所以運行了else
。
你想要更正常的if (a & (1<<2))
嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.