Path: utzoo!mnetor!uunet!yale!mfci!root From: root@mfci.UUCP (SuperUser) Newsgroups: comp.lang.c Subject: Re: anonymous functions Message-ID: <393@m3.mfci.UUCP> Date: 10 May 88 02:14:37 GMT References: <5773@sigi.Colorado.EDU> <11325@mimsy.UUCP> <282@teletron.UUCP> <11385@mimsy.UUCP> Reply-To: karzes@mfci.UUCP (Tom Karzes) Organization: Multiflow Computer Inc., Branford Ct. 06405 Lines: 58 Summary: Expires: Followup-To: Distribution: Keywords: In article <11385@mimsy.UUCP> chris@mimsy.UUCP (Chris Torek) writes: >In article <282@teletron.UUCP> andrew@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); } > ); > } Of course, this opens a whole can of worms about how to handle up-level references to automatics, etc. For example, what does the following do? int x = 123; main() { int x = 456; void (*fp)() = void () { printf("%d\n", x); }; (*fp)(); } You could make the reference to x illegal, but it wouldn't last. Some implementations would give you the external x, so you'd get 123, and others would give you the local x, so you'd get 456. The latter would be more generally powerful and useful, but then you'd have to have displays, etc. You'd also be put in the position of justifying why named nested functions aren't supported, and you'd end up having to support those as well... >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)(); > } Don't you mean: void foo() { void (*fp)() = void () { code }; ... (*fp)(); }