Is the macro-function preprocessor versus function pointer the best practice?

I recently created a small small project (the RGB value for the BGR value conversion program), and I realized that a function that converts from RGB to BGR can perform not only conversion, but also inversion. Obviously, this means that I really do not need the two functions rgb2bgr and bgr2rgb . However, it matters whether I use a function pointer instead of a macro? For example:

 int rgb2bgr (const int rgb); /* * Should I do this because it allows the compiler to issue * appropriate error messages using the proper function name, * not to mention possible debugging benefits? */ int (*bgr2rgb) (const int bgr) = rgb2bgr; /* * Or should I do this since it is merely a convenience * and they're really the same function anyway? */ #define bgr2rgb(bgr) (rgb2bgr (bgr)) 

I am not necessarily looking for changes in performance, since it is rather a subjective question out of curiosity. I am well aware that type safety is not lost and cannot be obtained using any method. Will the function pointer just be convenient or are there more practical advantages that I don't know about?

+6
c
source share
2 answers

Another possibility would be just the first call to the second function and let the compiler worry about optimizing it (by inserting or creating a tail call).

+6
source share

I would use a macro. It is more common and more idiomatic and faces fewer problems crossing translation units (i.e. you don't have to worry about declaring a macrostat).

In addition, by using a function pointer, you prevent most compilers from being embedded.

Finally, using a function pointer is possible for clients:

 int evil(const int bgr) { /* Do something evil */ } bgr2rgb = evil 

Of course, they probably do not want this, but it is possible that there may be a variable in the string with a name similar to bgr2rgb , where only one typo is required ....

A macro is safer, although I would define it this way - there is no need for a functionally similar macro:

 #define bgr2rgb rgb2bgr 
+5
source share

All Articles