anonymous functions

Chris Torek chris at mimsy.UUCP
Wed May 11 05:22:18 AEST 1988


In article <393 at m3.mfci.UUCP> root at mfci.UUCP (SuperUser) writes:
>Of course, this opens a whole can of worms about how to handle up-level
>references to automatics, etc.

Just make it illegal.  If you want access to some `parent's' variables
(in quotes because to a large extent, the scoping is illusory), you must
pass them to the anonymous function:

>    int x = 123;
>    main() {
>        int x = 456;
>        void (*fp)() = void () { printf("%d\n", x); };
>        (*fp)();
>    }

becomes

	int x = 123;
	main() {
		int x = 456;
		void (*fp)(int) = void (int x) { printf("%d\n", x); };
		(*fp)(x);
	}

>You could make the reference to x illegal, but it wouldn't last.
>[stuff about displays deleted]

I admit it `tastes odd', yet I am not sure it would not last.  I
would much rather not require static links or displays; I feel that
these are often just excess baggage: that they are not worth their
cost.  In practise, when I need access to uplevel variables, I do
it through what I call contexts.  These are rather similar to the
class pointers C++ passes to class functions, which are accessed
via the keyword `this'.  In C, there is no keyword: you have to do
it yourself:

	struct hitcontext {
		char	*str;
		int	hits;
	};
	static void hits_helper(void *context, struct tentry *te) {
		struct hitcontext *f = context;
		if (strstr(te->te_name, f->str) != NULL)
			f->hits++;
	}
	int hits(char *str, struct table *t) {
		struct hitcontext hc;
		hc.str = str;
		hc.hits = 0;
		table_iterate(t, hits_helper, (void *)&hc);
		return (hc.hits);
	}

(This is a simplified version of some real code.)  In this case,
it would be nice to keep both the hitcontext structure declaration
and the hits_helper function definition local to function hits.
Not necessary---just as unnamed aggregates are not necessary---but
convenient.  Can you imagine C without unnamed char arrays?

	int main() {
		static char S1[] = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 
				    'o', 'r', 'l', 'd', '\n', 0 };
		static char S2[] = {'i', ' ', '=', ' ', '%', 'd', '\n', 0 };
		int i;

		printf(S1);
		...
		printf(S2, i);
		return (0);
	}

Yuck!

Admittedly, anonymous functions are less useful in C than anonymous
strings.

[me:]
>>	foo() {
>>		void (*fp)() = void () { code; }

>Don't you mean:
>	foo() {
>		void (*fp)() = void () { code };

Yes.  (Just a typographic error....)
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list