我最近在C語言中啓動了一個小型個人項目(RGB值到BGR值轉換程序),我意識到一個從RGB轉換爲BGR的函數不僅可以執行轉換,還可以執行反轉。顯然這意味着我並不需要兩個功能rgb2bgr
和bgr2rgb
。但是,我使用函數指針而不是宏是否重要?例如:預處理器「宏函數」與函數指針 - 最佳實踐?
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))
我不一定是在尋找執行效率的變化,因爲它更多是出於好奇的主觀問題。我清楚地知道,使用這兩種方法既不會損失也不會獲得類型安全。函數指針只是爲了方便嗎?還是有更多的實際好處可以獲得,但我並不知道?
就我個人而言,我只是想出了一個描述兩種用法的名字,比如'int swap_rb()';) – caf 2010-05-15 00:22:10
@caf:絕對是另一個好主意。它完全避免了這個問題,但它是一個合理的選擇。 +1 – Dustin 2010-05-15 01:54:15