function returning pointer to itself

T. William Wells bill at proxftl.UUCP
Mon Jul 18 19:52:55 AEST 1988


As I recall, the original discussion was on how to create a state
machine using functions for the states.  Anyway, as has been
pointed out, the function can't return a pointer to itself.  What
it can do is to return a structure which contains a pointer to
itself.

The following code compiles and runs fine on our Sun.  It should
also be valid in Standard C.

typedef struct STR {
	struct STR (*func)();
} STR;

STR     Str;

STR     func1();
STR     func2();
STR     func3();

main()
{
	Str.func = func1;
	while (1) {
		Str = (*Str.func)();
	}
}

STR
func1()
{
	STR     str;

	printf("function 1\n");
	str.func = func2;
	return (str);
}

STR
func2()
{
	STR     str;

	printf("function 2\n");
	str.func = func1;
	return (str);
}

STR
func3()
{
	printf("function 3\n");
	exit(0);
}



More information about the Comp.std.c mailing list