anonymous functions

SuperUser root at mfci.UUCP
Tue May 10 12:14:37 AEST 1988


Expires:

Followup-To:

Distribution:

Keywords:


In article <11385 at mimsy.UUCP> chris at mimsy.UUCP (Chris Torek) writes:
>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); }
>		   );
>	}

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)();
	}



More information about the Comp.lang.c mailing list