Bitwise operators work on bits, logical operators evaluate boolean expressions. As long as expressions return bool, why don\'t we use bitwise operators instead
The answer is yes, you can. The question is why would you want to? I can name a few reasons you shouldn't:
bool, which can lead to subtle bugs.To illustrate the last point:
bool f1() {
cout << "f1" << endl;
return true;
}
bool f2() {
cout << "f2" << endl;
return true;
}
int main() {
if (f1() || f2()) {
cout << "That was for ||" << endl;
}
if (f1() | f2()) {
cout << "That was for |" << endl;
}
return 0;
}
It prints:
f1
That was for ||
f1
f2
That was for |
Assuming f2 may have significant side effects (if (okToDestroyWorld && destroyWorld()) ...), the difference can be enormous. It wouldn't surprise a Java programmer (where | and || actually defined for booleans by the language specification), but it is not a usual practice in C++.
I can think of just one reason to use a bitwise operator for booleans: if you need XOR. There is no ^^ operator, so if (a ^ b) is fine as long as both a and b are bool and there are no side effects involved.