Higher order functions in C

后端 未结 8 1721
小鲜肉
小鲜肉 2020-12-05 19:31

Is there a \"proper\" way to implement higher order functions in C.

I\'m mostly curious about things like portability and syntax correctness here and if there are mo

8条回答
  •  青春惊慌失措
    2020-12-05 19:56

    In straight c, this is really only done through function pointers, which are both a pain and not meant for this type of thing (which is partially why they are a pain). Blocks (or closures, according to non-apple) are fantastic for this, though. They compile in gcc-4.x or something, and icc something, but regardless thats what you're looking for. Unfortunately, I can't seem to find any good tutorials online, but suffice to say it works something like this:

    void iterate(char *str, int count, (^block)(str *)){
      for(int i = 0; i < count; i++){
        block(list[i]);
      }
    }
    
    main() {
      char str[20];
      iterate(str, 20, ^(char c){
        printf("%c ", c);
      });
    
      int accum = 0;
      iterate(someList, 20, ^(char c){
        accum += c;
        iterate(str, 20, ^(char c){
          printf("%c ", c);
        });
      });
    }
    

    obviously this code is pointless, but it it prints each character of a string (str) with a space in between it, then adds all of the characters together into accum, and every time it does it prints out the list of characters again.

    Hope this helps. By the way, blocks are very visible in Mac OS X Snow Leopard api-s, and I believe are in the forthcoming C++0x standard, so they're not really that unusual.

提交回复
热议问题