This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

unexpected behavior with bitwise-NOT operator in if() statement

I ran across something unexpected during development on our custom board today.

I checked the behavior on an nRF52840-Preview-DK board and was able to reproduce it:

This is the very simple code to reproduce the issue:

#include <stdint.h>


int main(void)
{
  volatile uint32_t i = 0;
  volatile uint32_t j = 0;
  uint8_t a,b,c,d;
  uint32_t z = 0;

  for(;;)
  {
    i++;
    j--;

    a = 0x0D;
    b = ~a;
    if(a != ~b)
    {
      z++;  // failed attempt 1
    }

    if(a != ~(b))
    {
      z++;  // failed attempt 2
    }

    if(a != (~b))
    {
      z++;  // failed attempt 2
    }

    c = ~b;
    if(a != c)
    {
      z--;  // failed last attempt
    }

  }

}

All of the if() statements test true (unexpected) except for the "if(a != c)" statement (where the bitwise-NOT is performed outside of the if() statement)

Any insight into what's going on here?

I'm using Segger Embedded Studio Release 4.16  Build 2019032803.38728.

  • Hi,

    you have declared your variables as uint8_t. As our CPU is 32-bit, all operations are performed with 32-bit values, and 8-bit variables are extended to 32 bits. In first three cases, 32-bit (~b) gives 0xffffff0d that is != 0x0d. In last case, result is shrinked to 8 bits to fit into 8-bit variable c, and result of comparison is false (0x0d == 0x0d).

Related