When assigning to or from a void-pointer no cast is needed (C99 §6.3.2.2 sub 1 / §6.5.16.1 sub 1). Is this also true when passing a (for example int-)pointer to a function that expects a void-pointer?
For example:
void foo(void * p){
// Do something
}
int main(){
int i = 12;
foo(&i); // int * to void *: no cast needed?
}
When I compile this with GCC (4.8.1, MinGW-32) I get neither errors nor warnings (with -Wall & -pedantic).
In contrast in this answer it is suggested that a cast is needed for this call (to eliminate -Wformat warnings):
int main(){
int i = 12;
printf("%p\n", &i);
}
But in my case GCC doesn't complain.
So: are casts needed when passing a non-void-pointer to a function that expects a void-pointer?
The difference is
printfis a variadic function and variadic functions follow different conversion rules on their trailing arguments.no cast is needed here as
foois a prototyped function. C says&iis converted to the type ofpas if by assignment and in C there is an implicit between all object pointer types tovoid *.The case with
printfis different as variadic functions likeprintfhave default argument promotions on their remaining arguments and no conversion occur on the argument of pointer types.C on prototyped functions:
C on variadic functions:
So: are casts needed when passing a non-void-pointer to a function that expects a void-pointer?
For
printf,pconversion specifier requires avoid *argument. If the argument is of a different type, the function call invokes undefined behavior. So if the argument ofpis an object pointer type, the(void *)cast is required.