c - Why it is recommended to cast a pointer to a generic one before printing? -


ok, have heard things should cast pointer generic 1 i.e void * before printing , must practice use of %p placeholder instead of %d in printf function printing them.

i have feeling might done prevent truncation of large addresses while printing or else? point if on machine 64 bit pointers , 32 bit integers; use of %p instead of %d solely job.

is aware of practical situations casting technique helpful?

because specification of %p specifier prints void *. doesn't know how print other type of pointer.

with printf caller must convert argument right type ; printf function cannot perform conversions because not have access type information arguments passed in. can assume passed right ones.

c99 7.19.6.1#7

p argument shall pointer void. value of pointer converted sequence of printing characters, in implementation-defined manner.

c99 7.19.6.1#9

if argument not correct type corresponding conversion specification, behavior undefined.

"undefined behaviour" means can happen. in practice, away if pointer pass has same size , representation void * does. should not rely on undefined behaviour.

on modern systems, object pointers (i.e. not function pointers) have same size , representation. if know on such system, , not important if program misbehaves, away passing wrong pointer type.

one place important if try print function pointer; there modern systems have function pointers different size object pointers. it's not guaranteed casting function pointer void * allowed compiler, @ least you'll compiler error message when try it.


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -