Reputation: 49
In the following code, I check if the result of the logical AND operation equals zero:
#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;
}
The output is: It got here!
However, if I don't use the "result" variable:
#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;
}
It doesn't print anything. Why does this happen?
Upvotes: 0
Views: 98
Reputation: 13526
The ==
operator has higher precedence than the &
operator. So your if statement is equivalent to
num1 & (num2 == 0)
Since num2 == 0
is true this works out to 0 & 1
which is 0.
Most compilers will warn in this situation if you have warnings enabled.
Upvotes: 1