Typecast of Pointers to Functions

Theodore Stevens Norvell norvell at csri.toronto.edu
Wed Mar 29 10:13:43 AEST 1989


In article <7689 at killer.Dallas.TX.US> brian asks:
>I am looking for an equivalent way to specify a typecast of a pointer to 
>a function other than using typedef.  For Example:
>  int         (*fcn_ptr2) (); 
>
>  fcn_ptr2 = (???????) NULL;  /* Do Not Use the typedef.  What Goes Here? */

Try   fcn_ptr2 = (int (*)()) NULL ;

The basic rule for type casts is that they look the same as a declaration
of a single identifier except (a) no semi-colon, (b) parentheses around it,
and (c) no identifier.  So it's really very simple.

To read a cast, just figure out where the only spot the identifier could
go is and then its understood the same as you understand declarations.

There is one more rule which says that parentheses that are in the cast,
but aren't used to indicate a function, must contain something.  This
rule is to avoid ambiguity and to make people who understand it feel
better.  E.g., this is a valid declaration for a pointer to a char
	char *(pc) ;
but _this_ is not going to cast to that type
	(char *())
but rather to a function returning a pointer to a char.  Without the
final rule an identifier could go in the parentheses, but with the
rule, it could only go after the *. So it's not all that simple after
all.

By the way.  In most versions of C (including ANSI), you shouldn't _need_
to cast NULL when you assign it, since the compiler can figure out what
to do.  

Theodore Norvell




More information about the Comp.lang.c mailing list