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.

+3


source to share


2 answers


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

,

+8


source


1

is an integer, so this expression matches int

. With this type of comparison, it turns out 0 == 256

. Otherwise, you are forcing and with only 8 digits, so the comparison is done.



+2


source







All Articles