function returning pointer to itself

Dave Jones djones at megatest.UUCP
Sun Jul 17 12:43:53 AEST 1988


>From article <7725 at watdragon.waterloo.edu), by smking at lion.waterloo.edu (Scott M. King):
) In article <5485 at batcomputer.tn.cornell.edu) olson at tcgould.tn.cornell.edu (olson) writes:
))Does the new C standard have a natural way to declare a
))function that returns a pointer to itself
)
) void *(*
) main() )()
) {
) 	return main;
) }
) 
) Ugly eh???
) --
) 
) Scott M. King


Ugly? Yes. Correct?  No.  Don't feel too bad, though.

1. C declarators are notoriously archane, and
2. There's no way to do it, anyway.

In the example you give, "main" is declared as 

	a funtion returning a pointer to
	a funtion returning a pointer to
	void

For a funtion to return a pointer to a function declared like main,
it would have to be declared as

	a funtion returning a pointer to
	a funtion returning a pointer to
	a funtion returning a pointer to
	void

You are always going to be off by one level of "pointering".
And what's "void" got to do with anything, anyway?

The problem is that there is no mechanism for forward-referencing
function _types_.  Compare with structure declartions:

	struct foo
	  { struct foo* ref;
	    int bar;
	  };

Here struct foo references its own declaration.  There's no
equivalent mechanism for declarators or typedefs.

The following would work, except for the fact that the basetype
(the first reference to "proc_ptr") is not defined at the point where
it occurs.

	typedef proc_ptr (*proc_ptr)();
                ^^^^^^^^
error: unknown basetype proc_ptr

A neat way to fix it would be to have forward declarations for types:

	typeforward proc_ptr;  /* Declare proc_ptr to be some
			       ** as yet undefined type.
			       */

	typedef proc_ptr (*proc_ptr)(); /* Declare it recursively */

The type-equivalence checker would have to be written correctly, lest
it get into an infinite loop when checking to see if two such types
were equivalent. Notice that in effect, proc_ptr is 

		            a pointer to
	a funtion returning a pointer to
	a funtion returning a pointer to
	a funtion returning a pointer to

		.
		.
		.


That's what you want.  No amount of dereferencing results in "void".



		later,

		Dave J.



More information about the Comp.std.c mailing list