I believe that & and && is identical for two bool operands,
nevertheless it is better to use the boolean && if that is the intention.
& as well as && have a lower precedence than comparison operators,
so it does not change the meaning of the expression.
https://en.cppreference.com/w/cpp/language/operator_precedence
const uint8_t val1_targetValue = 1;
const uint8_t val2_targetValue = 2;
void setup() {
Serial.begin(115200);
for (uint8_t i = 1; i < 3; i++) {
for (uint8_t j = 1; j < 3; j++) {
if (checkFor(i, j)) {
Serial.println(F("different result"));
} else {
Serial.println(F("same result"));
}
}
}
}
bool checkFor(uint8_t v1, uint8_t v2) {
bool var1 = (v1 == val1_targetValue && v2 == val2_targetValue);
bool var2 = (v1 == val1_targetValue & v2 == val2_targetValue);
Serial.print(v1);
Serial.print(F(" == "));
Serial.print(val1_targetValue);
Serial.print(F(" && "));
Serial.print(v2);
Serial.print(F(" == "));
Serial.print(val2_targetValue);
Serial.print(F(" gives "));
Serial.println(var1 ? "true" : "false");
Serial.print(v1);
Serial.print(F(" == "));
Serial.print(val1_targetValue);
Serial.print(F(" & "));
Serial.print(v2);
Serial.print(F(" == "));
Serial.print(val2_targetValue);
Serial.print(F(" gives "));
Serial.println(var2 ? "true" : "false");
return var1 != var2;
}
void loop() {}
1 == 1 && 1 == 2 gives false
1 == 1 & 1 == 2 gives false
same result
1 == 1 && 2 == 2 gives true
1 == 1 & 2 == 2 gives true
same result
2 == 1 && 1 == 2 gives false
2 == 1 & 1 == 2 gives false
same result
2 == 1 && 2 == 2 gives false
2 == 1 & 2 == 2 gives false
same result
The usage of & like this will trigger a warning:
Somewhere\oneortwoampersands.ino:19:19: warning: suggest parentheses around comparison in operand of '&' [-Wparentheses]
bool var2 = (v1 == val1_targetValue & v2 == val2_targetValue);
~~~^~~~~~~~~~~~~~~~~~~