c - Casting pointer to void when printing -


i've been trying work through c fundamentals lately try , build basic understanding of lower level languages. in 1 of documents i've encountered (a tutorial on pointers , arrays in c) author uses void pointer in printf statement:

int var = 2; printf("var has value %d , stored @ %p\n", var, (void *) &var); 

and states reason:

i cast pointers integers void pointers make them compatible %p conversion specification.

however, omitting (void *) not result in error or warning, either compiling , running or running through valgrind.

int var = 2; printf("var has value %d , stored @ %p\n", var, &var); 

is casting void here considered best practice or standard, or there more sinister afoot?

since printf variadic function, declaration specifies type of first parameter (the format string). number , types of remaining parameters required match format string, it's you, programmer, make sure match. if don't, behavior undefined, compiler isn't obliged warn it. (some compilers, including gcc, can checking if format string literal.)

the %p format specifier requires argument of type void*. if pass pointer of different type, have undefined behavior. in many implementations, pointer types have same size , representation, , passed same way function arguments -- language doesn't guarantee that. explicitly converting pointer void*, guarantee work correctly. omitting cast, have code probably work expect on implementations.

100% correct better 99% correct, if cost of 1% typing few characters.


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -