[cfe-dev] Assigning NULL

James Widman widman at gimpel.com
Tue Nov 13 21:19:16 PST 2007


On Nov 13, 2007, at 9:21 PM, Sanghyeon Seo wrote:

> The following is a typical pattern in many C programs.
>
> #include <stddef.h>
>
> typedef void (*hookfunc)(void *arg);
> hookfunc hook;
>
> void clear_hook() {
>   hook = NULL;
> }
>
> Should this warn?
> test.c:7:8: warning: incompatible pointer types assigning 'void *'  
> to 'hookfunc'

No.

Generally, you cannot convert from ptr-to-void to ptr-to-func, but a  
null pointer constant (like ((void*)0) in the example above) is a  
special case.  See C99, 6.3.2.3 (Pointers):

     1 A pointer to void may be converted to or from a pointer to
       any incomplete or object type. A pointer to any incomplete
       or object type may be converted to a pointer to void and
       back again; the result shall compare equal to the original
       pointer.

     2 For any qualifier q, a pointer to a non-q-qualified type
       may be converted to a pointer to the q-qualified version of
       the type; the values stored in the original and converted
       pointers shall compare equal.

     3 An integer constant expression with the value 0, or such an
       expression cast to type void *, is called a null pointer
       constant. If a null pointer constant is converted to a
       pointer type, the resulting pointer, called a null pointer,
       is guaranteed to compare unequal to a pointer to any object
       or function.

     4 Conversion of a null pointer to another pointer type yields
       a null pointer of that type.  Any two null pointers shall
       compare equal.


James Widman
-- 
Gimpel Software
http://gimpel.com





More information about the cfe-dev mailing list