Higher order functions in C

后端 未结 8 1607
小鲜肉
小鲜肉 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:39

    If you want to create higher order functions, don't use C. There are C solutions to your problem. They may not be elegant, or they may be more elegant that you realize.

    [Edit] I suggested that the only way to achieve this was to use a scripting language. Others have called me out on it. So, I'm replacing that suggestion with this: [/Edit]

    What are you trying to achieve? If you want to mimic closures, use a language that supports them (you can tie into Ruby, lua, javascript, etc through libraries). If you want to use callbacks, function pointers are ok. Function pointers combine the most dangerous areas of C (pointers and the weak type system), so be careful. Function pointer declarations are not fun to read, either.

    You find some C libraries using function pointers because they have to. If you're writing a library, maybe you need to use them, too. If you're just using them within your own code, you're probably not thinking in C. You're thinking in lisp or scheme or ruby or ... and trying to write it in C. Learn the C way.

提交回复
热议问题