fly swatter fly swatter - 3 months ago 10
C Question

c good programing practice using #define and hex values instead of decimal

I'm trying to improve my coding practice for embedded. The code below writes the value 0
to the memory location

0x80001000
.

#define MemoryWrite(A,V) *(volatile unsigned long*)(A)=(V)
#define FLAG 2147487744 //0x80001000

uint32_t reset_value = 0;

int main(void)
{
MemoryWrite(FLAG, reset_value);
return 0;
}


I have two questions:


  1. In order to use the MemoryWrite macro I had to convert
    0x80001000
    to
    2147487744
    .
    I think this is bad practice and unclear. Is there a way that I could do this just using the hex value?

  2. I'm nots sure if defining
    reset_value
    as a
    uint32_t
    is good practice. Could I do this as a
    #define
    .


Answer
  1. In order to use the MemoryWrite macro I had to convert 0x80001000 to 2147487744. I think this is bad practice and unclear. Is there a way that I could do this just using the hex value?
#define FLAG 0x80001000u

When the u for unsigned is not present and because you have 4 bytes on a 32bit machine, the compiler assumes that the value is signed and 0x80001000 = -2147479552

  1. I'm not sure if defining reset_value as a uint32_t is good practice. Could I do this as a #define.

You can of course write #define RESET_VALUE 0. But the usefulness is not evident in such simple code. It depends if you want to modify the value in the future or not. The compiler will certainly optimize it in the same way for this 10 lines example.