Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- typedef int (*FN)(int n);
- struct ClosureData {
- int value;
- struct ClosureData *next;
- };
- FN summ(int x) {
- static struct ClosureData *closureData = NULL;
- int fn(int y) {
- struct ClosureData *next;
- int result;
- result = closureData->value + y;
- next = closureData->next;
- free(closureData);
- closureData = next;
- return result;
- };
- struct ClosureData *newData;
- newData = (struct ClosureData*)malloc(sizeof(struct ClosureData));
- if (!newData) {
- while (closureData) {
- newData = closureData->next;
- free(closureData);
- closureData = newData;
- }
- fprintf(stderr, "System error: can't allocate memory.\n");
- exit(1);
- }
- newData->value = x;
- newData->next = NULL;
- if (!closureData) {
- closureData = newData;
- } else {
- closureData->next = newData;
- }
- return fn;
- }
- int main(int argc, char *argv[]) {
- printf("Summ: %d\n", summ(2)(3)); // 5
- printf("Summ: %d\n", summ(4)(4)); // 8
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment