2011-10-20 115 views
6

可能重複:
function overloading in CANSI C和函數重載

ANSI C不允許函數重載(我不知道C99)。

例如:

char max(char x, char y); 
short max(short x, short y); 
int max(int x, int y); 
float max(float x, float y); 

不是有效的ANSI C源代碼。

在ANSI C中應該使用哪種技術(或想法)來解決函數重載問題?

注意

的答案被重命名功能,但模式應該用於重命名,該函數名稱保持「好函數名」

例如:

char max1(char x, char y); 
short max2(short x, short y); 
int max3(int x, int y); 
float max4(float x, float y); 

不是好的命名爲功能max名。

+1

也許定義一個'max'宏? ;-) –

+0

@DidierTrosset:max只是一個例子,圖像是一個非常複雜的功能。 –

+2

如果函數重載對你很重要,那麼也許你應該考慮使用C++而不是C? –

回答

11

使用的數據類型在功能名稱來評價,例如

char max_char(char x, char y); 
short max_short(short x, short y); 
int max_int(int x, int y); 
float max_float(float x, float y); 
+1

這就是標準庫所做的 - 例如我們有'atoi()','atol()','atof()'和'atod()'。 – caf

0

在本例中,正確的解決方案是使用一個宏。您也可以簡單地使用內聯函數,該函數採用最大可能的整數或浮點類型,並在知道參數較小時讓編譯器優化它。在簽名等方面你應該考慮一些角落案例,但是那些已經發生了。