c - pointer cast on embedded systems, byte pointer on 32bit variable via pointer cast -


i have read out bytes of uint32_t variable, , have seen kind of implementation colleague of mine. question is, if behaviour of code-example reliable on "nearly every" 32bit microcontroller. supposable work on every 32bit microcontroller or platform-specific behaviour relying on? p.s.: endianness of system shall not considered in example.

uint8_t     byte0=0; uint8_t     byte1=0; uint8_t     byte2=0; uint8_t     byte3=0; uint8_t     *byte_pointer;  //byte_pointer uint32_t    *bridge_pointer;//pointer_bridge between 32bit , 8 bit variable uint32_t    var=0x00010203;  bridge_pointer=&var;    //bridge_pointer point var byte_pointer=(uint8_t *)(bridge_pointer);   //let byte_pointer point bridge_pointer  byte0=*(byte_pointer+0);    //saves byte 0 byte1=*(byte_pointer+1);    //saves byte 1 byte2=*(byte_pointer+2);    //saves byte 2 byte3=*(byte_pointer+3);    //saves byte 3 

thanks in advance

byte0=*(byte_pointer+0);    //saves byte 0 

this line (and following ones) violation of strict-aliasing. object declared uint32_t accessed through lvalue of type uint8_t; unsigned char should used instead of uint8_t, lvalues of character type allowed access objects of different type (if uint8_t exists, behaves same unsigned char despite more relaxed aliasing rules).

unsigned char *byte_pointer = (unsigned char *)(bridge_pointer); uint8_t byte0 = *(byte_pointer+0);     // byte0 can still uin8_t, access var important aliasing 

as mentioned in comment, byte_pointer[0] equivalent *(byte_pointer+0) , more common.

with change, code has well-defined behaviour. (and portable implementations having uint32_t , uint8_t, although endianness may lead different results, noted in question.)

the relevant standard parts strict aliasing 6.5 p6/7.


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -