Guest User

Closure in gcc

a guest
Nov 30th, 2022
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.13 KB | Source Code | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. typedef int (*FN)(int n);
  5.  
  6. struct ClosureData {
  7.     int value;
  8.     struct ClosureData *next;
  9. };
  10.  
  11. FN summ(int x) {
  12.     static struct ClosureData *closureData = NULL;
  13.     int fn(int y) {
  14.         struct ClosureData *next;
  15.         int result;
  16.         result = closureData->value + y;
  17.         next = closureData->next;
  18.         free(closureData);
  19.         closureData = next;
  20.         return result;
  21.     };
  22.     struct ClosureData *newData;
  23.     newData = (struct ClosureData*)malloc(sizeof(struct ClosureData));
  24.     if (!newData) {
  25.         while (closureData) {
  26.             newData = closureData->next;
  27.             free(closureData);
  28.             closureData = newData;
  29.         }
  30.         fprintf(stderr, "System error: can't allocate memory.\n");
  31.         exit(1);
  32.     }
  33.     newData->value = x;
  34.     newData->next = NULL;
  35.     if (!closureData) {
  36.         closureData = newData;
  37.     } else {
  38.         closureData->next = newData;
  39.     }
  40.     return fn;
  41. }
  42.  
  43. int main(int argc, char *argv[]) {
  44.     printf("Summ: %d\n", summ(2)(3)); // 5
  45.     printf("Summ: %d\n", summ(4)(4)); // 8
  46.     return 0;
  47. }
Tags: GCC closure
Advertisement
Add Comment
Please, Sign In to add comment