1

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

3
  • 1
    what is uint8 ? If it's a typedef for an 8-bit integer type then this code is pretty weird. val > 255 would be redundant, and it's a bit strange to pass your memory address (in the range 0-255) as an integer instead of a pointer. Commented Dec 10, 2015 at 22:41
  • uint8 is the same uint8_t == unsigned character. the condition for val > 255 is just a test measure for me. this function should get the address of the required register to initialize with some value so the argument reg should be 8-bits. Commented Dec 11, 2015 at 14:09
  • Pass the register as address: "static inline uint8 init_reg(uint8 *reg, uint8 val)", example call: "init_reg(&PORTX, 0)". Commented Feb 14, 2023 at 4:45

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

8 Comments

"casting a shorter integer into a pointer might inadvertently zero out the higher bits." - huh?
@M.M Bad choice of words. What i meant is that using a shorter integer to store a memory address might miss the high bits.
I see, you're referring to when this function is being called. Surely using a pointer type would be the best way to avoid this though.
@M.M The issue with these embedded devices is that there are memory mapped registers at well known addresses. And these addresses have to be entered as numeric constants, so you must do the cast from integer to pointer somewhere.
Yeah, do it once at the start of the program, and then take advantage of type safety for the rest of the code.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.