Comparing uint8_t with a number

Amomum picture Amomum · Sep 26, 2013 · Viewed 9.6k times · Source

Maybe I do not understand C++ properly or is it a compiler's bug?

uint8_t a = 0x00;
uint8_t b = 0xFF;

if( a - b == 1 )
{
    doNothing();
}

doNothing is not called (as expected), because result of (a-b) was implicitly casted to the type of second operand in compare operation. And for numbers it's signed int. Okay.

if( a - b == (uint8_t)1 )
{
    doNothing();
}

doNothing STILL isn't called, but now I do not understand the reason for it! I have explicitly casted the number to uint8!

if( (uint8_t)(a - b) == 1 )
{
    doNothing();
}

Now doNothing is finally called, but again why? How can subtraction of two uint8 return an int?

Compiler is uVision ARMCC for ARM Cortex M3.

Answer

Mike Seymour picture Mike Seymour · Sep 26, 2013

In a - b, the operands are promoted to int before the subtraction, so the result is -255, not 1.

That's why both the first and second examples fail; it's nothing to do with the other operand of ==. The third converts -255 back to uint8_t, reducing it modulo 256, so the result is 1 as expected.