[英]Unexpected result of logical AND operation between two uint64_t numbers
在以下代碼中,我檢查邏輯 AND 運算的結果是否為零:
#include <iostream>
#include <cstdint>
int main() {
uint64_t num1 = 0b0000000000000000000000000000000000000000000000000000000000000000;
uint64_t num2 = 0b0000000000000000000000000000000000000000000000000000000000000000;
uint64_t result = num1 & num2;
if(result == 0) {
std::cout << "It got here!\n";
}
return 0;
}
輸出是:它到了!
但是,如果我不使用“result”變量:
#include <iostream>
#include <cstdint>
int main() {
uint64_t num1 = 0b0000000000000000000000000000000000000000000000000000000000000000;
uint64_t num2 = 0b0000000000000000000000000000000000000000000000000000000000000000;
if(num1 & num2 == 0) {
std::cout << "It got here!\n";
}
return 0;
}
它不打印任何東西。 為什么會發生這種情況?
==
運算符的優先級高於&
運算符。 所以你的 if 語句相當於
num1 & (num2 == 0)
由於num2 == 0
為真,這適用於0 & 1
,即 0。
如果您啟用了警告,大多數編譯器會在這種情況下發出警告。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.