Why does this comparison return false?

c

Solution

Because of integer promotions, both operands of the `==` and `+` operator are promoted to `int`.

The expression:

a == (b + 1)

is then equivalent to:

0 == 256

which is false.

The expression: `a == (uint8_t) (b + 1)` would give you the result you expect (true). Another solution is to use `& 0xFF` like in your second `if` statement,

Problem

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 unless I forcibly take the last 8 bits? I'm guessing I'm missing some nuance of unsigned arithmetic here... I'm using gcc 4.4.5 if that makes a difference.

Original source