Argument conversion: (normal) pointer to void pointer, cast needed?

纵然是瞬间 提交于 2019-11-29 10:37:57

The difference is printf is a variadic function and variadic functions follow different conversion rules on their trailing arguments.

foo(&i); 

no cast is needed here as foo is a prototyped function. C says &i is converted to the type of p as if by assignment and in C there is an implicit between all object pointer types to void *.

The case with printf is different as variadic functions like printf have default argument promotions on their remaining arguments and no conversion occur on the argument of pointer types.

C on prototyped functions:

(C99, 6.5.2.2p7) "If the expression that denotes the called function has a type that does include a prototype, the arguments are implicitly converted, as if by assignment, to the types of the corresponding parameters, taking the type of each parameter to be the unqualified version of its declared type."

C on variadic functions:

(C99, 6.5.2.2p7) "(C99, 6.5.2.2p7) "The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments."

So: are casts needed when passing a non-void-pointer to a function that expects a void-pointer?

For printf, p conversion specifier requires a void * argument. If the argument is of a different type, the function call invokes undefined behavior. So if the argument of p is an object pointer type, the (void *) cast is required.

(C99, 7.19.6.1p8) "p The argument shall be a pointer to void."

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!