NOTE: After performing a blog import WordPress messed my code . If you see any problems please let me know .
In order to prove that generic programming (the style of computer programming in which algorithms are written in terms of to-be-specified-later types that are theninstantiated when needed for specific types provided as parameters) can be achieved in C, let’s write the implementation of a generic Stack data structure . We will follow two possible approaches:
- Hacking with the #preprocessor;
- Using the flexibility of the void pointer (void*);
You can always try both of the approaches and see which one is more suitable for your particular case . Also note that there are already generic C libraries available (see GLib ).
1. Hacking with the preprocessor
To understand the magic (not really) behind this approach you will need to be familiar with C macros and the associated concepts: function-like macros, macro arguments, stringification and concatenation. You can find a very nice tutorial on macros here. If you already know your stuff, you can skip the following paragraphs (or you can read them to refresh your memory / find errors and correct me :P). Read More