c preprocessor - What does this C macro mean? -


looking @ fm_transmitter source code, came across macro, used quite often.

#define access(base, offset) *(volatile unsigned*)((int)base + offset) 

i guess sum of base , offset casted int, re-casted unsigned pointer , again pointer?

this macro provides access offset measured in bytes. rewrite as

#define access(base, offset) *(volatile unsigned*)&((char*)base)[offset] 

only original version arithmetic via int type instead of char* type.

note use of macro invokes undefined behavior: resulting pointer not guaranteed aligned, , if data written other type int variant, it's violation of strict aliasing rules well.

also, choice of int pointer arithmetic poor choice, calculation should @ least done via size_t or uintptr_t guarantee pointer not truncated during cast integer type. rewritten version not have specific problem, however, danger of undefined behavior remains both versions.

finally, olaf rightly noted in comments, it's bad idea cast volatile unsigned* since width of type implementation defined. cast volatile uint32_t* more appropriate communication hardware.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

android - Keyboard hides my half of edit-text and button below it even in scroll view -