Default parameters in C

2019-02-02 21:10发布

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.

4条回答
淡お忘
2楼-- · 2019-02-02 21:23

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
}
查看更多
Luminary・发光体
3楼-- · 2019-02-02 21:27

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.

查看更多
▲ chillily
4楼-- · 2019-02-02 21:34

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");
    }

}
查看更多
Rolldiameter
5楼-- · 2019-02-02 21:45

Default parameters is a C++ feature.

C has no default parameters.

查看更多
登录 后发表回答