Products > Programming

GCC ARM32 comparison question

(1/8) > >>

peter-h:

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

if (a != ~b)
{
  fred=true;
}

// now fred=true

b=~b;
fred=false;
if (a != b)
{
  fred=true;
}

// 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 ---

Siwastaja:
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
https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B

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))

peter-h:
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

~0

becomes

0xffffffff

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.

SiliconWizard:
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.

Navigation

[0] Message Index

[#] Next page

There was an error while thanking
Thanking...
Go to full version