Search code examples
ccurrying

How to do currying in C


In this code I am trying to return a function that can add ctx.a to passed argument x. The intended answer is 4 but when running this code it prints 6. What is going wrong here?

I have tried this code:

#include <stdio.h>

typedef struct {
  int a;
} ctx_t;

typedef void(*with_ctx)(int);

with_ctx create_handler(ctx_t ctx) {
  void handler(int x) {
    printf("%d\n", ctx.a + x);
  }

  return handler;
}

int main() {

  ctx_t ctx = { .a = 1 };
  with_ctx handler = create_handler(ctx);
  handler(3);

  return 0;
}

Solution

  • Declaring functions inside functions is not supported in C. What happens, is that you are using a compiler that supports it as an extension on top of C. I thin only gcc supports it.

    What is going wrong here?

    What then happens is that the variable ctx stops existing after return handler;. The variable ctx scope inside create_handler stops existing after the function ends on }. So calling handler() will access some undefined region of memory, where ctx used to be. It is no longer there.

    It is not possible to create lambdas in C programming language. See Is there a way to do currying in C? .