Remix.run Logo
mananaysiempre 5 hours ago

Good C style is that every function that accepts a callback should also accept an opaque context pointer it then passes through unchanged to the callback. Usually the caller will allocate a structure on the stack or the heap, stash some of its local variables there, then use them in the callback. A nested function does the structure back-and-forth for you in the stack-allocated case. In GCC’s original formulation it also passes the context pointer implicitly

  size_t filter(bool (*predicate)(int), int *p, size_t n) {
      for (size_t r = 0, w = 0; r < n; r++) {
          if (predicate(p[r])) p[w++] = p[r];
      }
      return w;
  }
  size_t lowpass(int limit, int *p, size_t n) {
      bool lower(int value) {
          return value < limit; // use the parent's local variable
      }
      return filter(lower, p, n);
  }
but that requires an executable stack and TFA is about avoiding that part.