Default parameters in C

早过忘川 提交于 2019-11-28 23:40:40

问题


Is it possible to set values for default parameters in C? For example:

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

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

Visual Studio 2008, complaints that there is a syntax error in -void display(int a, int b=10). If this is not legal in C, whats the alternative? Please let me know. Thanks.


回答1:


Default parameters is a C++ feature.

C has no default parameters.




回答2:


It is not possible in standard C. One alternative is to encode the parameters into the function name, like e.g.

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

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



回答3:


There are no default parameters in C.

One way you can get by this is to pass in NULL pointers and then set the values to the default if NULL is passed. This is dangerous though so I wouldn't recommend it unless you really need default parameters.

Example

function ( char *path)
{
    FILE *outHandle;

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

}



回答4:


Not that way...

You could use an int array or a varargs and fill in missing data within your function. You lose compile time checks though.



来源:https://stackoverflow.com/questions/9185429/default-parameters-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!