Products > Programming

GCC ARM32 comparison question

(1/8) > >>


--- Code: --- volatile uint8_t a=0xaa;
volatile uint8_t b=0x55;
volatile bool fred=false;

if (a != ~b)

// now fred=true

if (a != b)

// now fred=false

--- End code ---

How does this work? Does inverting a byte produce some larger variable? Even this doesn't work:

--- Code: ---if (a != (~b))
--- End code ---

This is basic C, you can Google it all, or read any tutorial - and of course, the standard itself (any version really). Instead of direct answer, let me help you with keywords:

C operators:
~ operator
!= operator

C integer promotion

BTW, from the strange way of using volatile I'm assuming you are flashing this on an MCU target and looking at it in debugger, am I right? But IMHO, for simple "how does that language work" tests, I would prefer just having gcc installed on your PC, write a small program and use printf(). This easily extents to be a larger unit test where you can loop through possible values and check the correctness.

Nominal Animal:

--- Quote from: peter-h on June 17, 2022, 03:50:27 pm ---Does inverting a byte produce some larger variable?
--- End quote ---
You forgot the automatic integer promotions C compilers (have to) do.  Everything smaller than int that can be described by an int, gets converted to an int, and so on.

The correct expression here is
if (a != (uint8_t)(~b))

Yes; embedded target. I really should set up Borland C v3.1 on my PC :)

I did suspect the uint8_t was being converted to an int, so




for the comparison (or some such).

The reason this has not caught me out before is because most of my 32F417 coding has been uint32_t, flipping bits destined for registers, etc.

Yep, integer promotion is the key to integer arithmetics in C. And yep, it can be a bit confusing and a bit annoying. As shown above, you'll need explicit conversions.


[0] Message Index

[#] Next page

There was an error while thanking
Go to full version