Why does this comparison return false?
In this little program:
#include <unistd.h>
#include <stdint.h>
#include <stdio.h>
int main() {
uint8_t a = 0;
uint8_t b = 255;
if (a == (b + 1)) {
printf("Equal\n");
} else {
printf("Not equal\n");
}
if (a == ((b + 1) & 0xFF)) {
printf("Equal\n");
} else {
printf("Not equal\n");
}
}
I get:
Not Equal
Equal
Why doesn't the comparison work if I can't get the last 8 bits? I am guessing that there is some nuance of unsigned arithmetic missing here ...
I am using gcc 4.4.5 if that matters.
source to share
Due to whole promotions, both operands of the ==
and operator are +
promoted to int
.
Expression:
a == (b + 1)
then equivalent to:
0 == 256
which is false.
Expression: a == (uint8_t) (b + 1)
will give you the result you expect (true). Another solution is to use & 0xFF
, as in your second expression if
,
source to share