Mina Emil
Mina Emil

Reputation: 13

Casting to pointer from integer of different size

I'm using Atmel Studio to build hex files for AVR microcontrollers. Every time I try to build a certain project while using the following function is generating a warning of casting to pointer from integer or different size.

The function is:

static inline uint8 init_reg(uint8 reg, uint8 val)
{
    if (val > 255)
        return E_FAIL;
    *(volatile uint8 *) (reg) = val;
    return S_PASS;
}

I want to know the cause of such warning. Thank you...

Upvotes: 1

Views: 1523

Answers (1)

rodrigo
rodrigo

Reputation: 98526

The warning is here because pointers in your architecture are 16 bits, IIRC, but the integer you are casting is not 16 bits in size, but 8 bits. And casting a shorter integer into a pointer might inadvertently zero out the higher bits.

The immediate solution is to cast it first to 16 bit integer, and then to pointer:

*(volatile uint8 *) (uint16) reg = val;

But I'd prefer to change the function prototype, if possible, to illustrate that the integer is an address:

static inline uint8 init_reg(uint16 reg, uint8 val)

BTW, your check if (val > 255) is useless, as a uint8 will never be higher than 255, so it is always false (no warning here?).

Upvotes: 3

Related Questions