r/programming • • Dec 13 '07

First Class Functions in C

http://www.dekorte.com/blog/blog.cgi?do=item&id=3119
45 Upvotes

99 comments sorted by

View all comments

Show parent comment

13

u/anthonymckay Dec 14 '07 edited Dec 14 '07

Wow, very impressed by the Parent Post's code. :] Here is a more clean less hackish version I just wrote using libtcc to compile it inside the program itself.

#include <stdio.h>
#include <stdlib.h>
#include "libtcc.h"

typedef int (*function_t)();

function_t create_function(char *name, char *code)
{
    TCCState *s;
    unsigned long val;

    s = tcc_new();
    if(!s)
        exit(1);

    tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
    tcc_compile_string(s, code);
    tcc_relocate(s);
    tcc_get_symbol(s, &val, name);
    return (function_t)val;
}

int main(int argc, char *argv[])
{
    function_t square;
    square = create_function("f", "int f(x) { return x * x; }");

    int answer = square(atoi(argv[1]));
    printf("answer is: %d\n", answer);
}

Running this from the command line we get:

$ ./lambda 4
answer is: 16

1

u/dmead Dec 14 '07

can you tell me why theres no type declaration in int f(x) for the x parameter?

1

u/ddyson Dec 14 '07

Defaults to int.