2012-02-07 91 views
25

是否可以为C中的默认参数设置值?例如:C中的默认参数

void display(int a, int b=10){ 
//do something 
} 

main(){ 
    display(1); 
    display(1,2); // override default value 
} 

Visual Studio 2008中,投诉,有在-void显示了语法错误(INT A,INT B = 10)。如果这在C中不合法,那有什么选择?请告诉我。谢谢。

+1

事实上,它在C中不合法。C也没有超载。 – Mysticial 2012-02-07 23:09:42

+0

可能的重复:http://stackoverflow.com/questions/1472138/c-default-arguments – 2012-02-07 23:11:27

+0

http://stackoverflow.com/questions/2988038/default-values-on-arguments-in-c-functions-and- function-overloading-in-c – 2014-04-23 05:52:53

回答

36

的默认参数是一个C++特征。

C没有默认参数。

4

有在C.没有默认参数,你可以通过这个获得

的一种方法是空指针传递,然后如果传递NULL值设置为默认值。这很危险,但我不会推荐它,除非你真的需要默认参数。

function (char *path) 
{ 
    FILE *outHandle; 

    if (path==NULL){ 
     outHandle=fopen("DummyFile","w"); 
    }else 
    { 
     outHandle=fopen(path,"w"); 
    } 

} 
9

这是不可能在标准C.一种替代方法是在参数编码成函数名,像例如

void display(int a){ 
    display_with_b(a, 10); 
} 

void display_with_b(int a, int b){ 
    //do something 
} 
+1

+1。我也喜欢在[这个答案](http://stackoverflow.com/a/1472310/790070)评论中的做法,其中函数的名称包括它所需的参数数目。 – 2012-02-07 23:15:56

1

不是这样的......

你可以使用一个int数组或一个可变参数,并在你的函数中丢失的数据填写。尽管如此,你会失去编译时检查