Ptr to func doesn't like casting??

greenber at acf4.UUCP greenber at acf4.UUCP
Sat Dec 1 10:30:00 AEST 1984


This is by far the most definitive example that I good
that I just couldn't help posting it  (John, I hope you forgive me!!)
Thank you John....and I bet this helps out others....

Ross -- I can understand your confusion, I got confused about the
same thing when I was "only an egg".  We have:

int (*varname)();	/* You're right, this is a
			 *	Pointer		 to a
			 *	Function	 returning an
			 *	int

char *function();	/* a function returning char *, clearly */

	varname = function();
will work on some, perhaps most, CPUs but will not lint; as you
say, why should it?  It is wrong.

	(char *)varname = function();
isn't C, as you found out; I can't understand why people want
to try writing that, it never occured to me.

Your other try:
	varname = (*function())();
is a real doozy!  Like, it's semantically very different (and sure as hell
won't lint, let alone working).  It says:
	Invoke function(), get a char *
	Apply * to that, getting a char
	Coerce the char into a (deep breath):
		pointer to a
		function returning a
		pointer to a
		function returning an
	[this is "implied but not stated"]
	Invoke the pointed-to function (!) [the second set of () means this]
	Store the result in varname.
So you can see there are TWO function calls there, and the second one had
its address made out of a char, which is hardly likely to do anything good.
This is most unlikely to compile on any modern compiler, and I do not think
even a V6-style "lax" compiler would let it go by unchallenged.

So, you ask, what do I do?  Well, it's simple when you know how:

	varname = (int (*)())function();

That's the cast you want.  A useful rule to help you construct casts to complex
types is:
	Think of a declaration for a variable of that type
			[ int (*fp)(); ]
	Take the identifier out, lose the semicolon
			[ int (*)() ]
	Enclose the whole thing in parentheses
			[ (int (*)()) ]

Just by the way, our "lint" (we're running a heavily hacked V7) says that
this is a "questionable conversion of function pointer".  And it
probably is, too.  (SysVr2 lint says the same.)  But at least that's
the correct cast!

John Mackin, Physiology Department, University of Sydney, Sydney, Australia

More information about the Comp.lang.c mailing list