Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

well I'm not the best when it comes to mathematics nor hex but it seems that a = 0 and b = 255 so it equals -255 not 1.

ARM Cortex M3 is a 32 bit processor. So result of a - b is 0xFFFFFF01 which is not equal to 1 (1 ==> 0x00000001 in 32 bit representation) so doNothing() function is not called!

In case 2, if you typecast 1 to uint8_t, which is 0xFFFFFF01 is not equal to 0x01 so doNothing() function not called again!

In case 3, when you typecast a - b output to uint8_t then a - b result is 0x01 which is equal to 1, hence doNothing is called.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top