anonymous functions

Chris Torek chris at mimsy.UUCP
Sat May 7 11:04:22 AEST 1988


>In article <11325 at mimsy.UUCP> I mentioned
>>(Of course, if you add unnamed aggregates, you should also add
>>unnamed functions.)

In article <282 at teletron.UUCP> andrew at teletron.UUCP (Andrew Scott) asks:
>... How would unnamed functions be implemented?  How would they be used?

The implementation is obvious (he said smugly).  You could even do it
in a PCC-style compiler:

	/* source */
	void bar(int (*fp)());	/* bar takes one argument */

	void
	foo() {
		bar(	/* call bar with the pointer from...: */
			/* (here comes the anonymous function def.) */
			int (){ int i; i = 3; return (i); }
		   );
	}

	/* sample dumb compiler output */
	_foo:	.globl	_foo
		sub	$L1,sp		# create local frame space
		jbr	L2		# branch around the anonymous fn.
	L3:
		sub	$L4,sp		# create local frame space
		mov	$3,-4(fp)	# i=3
		mov	-4(fp),r0	# return (i)
		ret
		.set	L4,4		# anonymous function (L3) needs
					# 4 bytes of stack
	L2:	push	$L3		# push address of anonymous fn.
		call	_bar		# bar(...)
		pop	r0		# clean up
		ret			# end of foo()
		.set	L1,0		# function foo needs 0 bytes

As for uses, anonymous functions are much like anonymous aggregates:
you use them to pass to other functions, or to set local variables
(in C, pointers to functions).

	void
	foo() {
		void (*fp)() = void () { code; }
		...
		(*fp)();
	}
-- 
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