Search code examples
cvariablesembeddeddeclaration

Understanding an embedded C language variable declaration


I'm trying to understand some embedded C code that declares a variable.

uint8_t *p=(uint8_t *)&NOCAN_REGS;

The NOCAN_REGS is a structure defined in a different file (see link below)

My understanding is that the variable "p" is a pointer to an unsigned 8 bit integer, but everything from the typecast after the equals sign is a mystery to me.

I would appreciate a step by step explanation, or a link to a learning resource that can help me master this syntax.


Solution

  • Okay, here is everything after the = sign:

    (uint8_t *)&NOCAN_REGS;
    

    Taken from right to left (because it's easier to explain in that order):

    NOCAN_REGS;
    

    ... this is the name of a global struct-object, as you mentioned.

    &
    

    The & sign indicates you want a pointer-to-whatever-is-after-it, so

    &NOCAN_REGS
    

    ... means "pointer to the NOCAN_REGS struct".

    (uint8_t *)
    

    The cast is here to forcibly change the type of the expression from nocan_registers_t * to uint8_t *. That is, you are telling the compiler that you want the expression's type to be pointer-to-unsigned-bytes, rather than a pointer-to-a-nocan_registers_t.

    Typically a programmer would do a cast like this when he wants to treat a struct's memory as if it were a raw byte-buffer. It's a tricky thing to do, since when you throw away the type-information like that, issues that the compiler normally takes care of for you (like the endian-ness of member-variables, their alignment to appropriate boundaries, padding bytes, etc) now become things the programmer has to think about... but it can be useful in cases where you want to e.g. dump the raw memory to disk or similar.