有没有一种方法可以在C语言中指定函数的默认参数?
当前回答
我知道如何更好地做到这一点。 您只需将NULL赋值给一个参数,因此,您将没有值。然后检查参数值是否为NULL,将其更改为默认值。
void func(int x){
if(x == NULL)
x = 2;
....
}
尽管如此,它还是会引起警告。一个更好的选择是,如果参数值是:
void func(int x){
if(x == 1)
x = 2;
....
}
在上面的例子中,如果x是1,函数将其更改为2;
感谢@user904963,编辑: 如果必须覆盖所有的数字范围,那么添加另一个参数来告诉函数是否将形参设置为默认并不难
void func(int x, bool useDefault){
if(useDefault) //useDefault == true
x = 2;
....
}
但是,请记住包含stdboolh
其他回答
OpenCV使用的是:
/* in the header file */
#ifdef __cplusplus
/* in case the compiler is a C++ compiler */
#define DEFAULT_VALUE(value) = value
#else
/* otherwise, C compiler, do nothing */
#define DEFAULT_VALUE(value)
#endif
void window_set_size(unsigned int width DEFAULT_VALUE(640),
unsigned int height DEFAULT_VALUE(400));
如果用户不知道他应该写什么,这个技巧会很有用:
不,但你可以考虑使用一组函数(或宏)来近似使用默认参数:
// No default args
int foo3(int a, int b, int c)
{
return ...;
}
// Default 3rd arg
int foo2(int a, int b)
{
return foo3(a, b, 0); // default c
}
// Default 2nd and 3rd args
int foo1(int a)
{
return foo3(a, 1, 0); // default b and c
}
一般不会,但在gcc中,你可以使用宏将funcA()的最后一个参数设置为可选的。
在funcB()中,我使用了一个特殊的值(-1)来表示我需要'b'参数的默认值。
#include <stdio.h>
int funcA( int a, int b, ... ){ return a+b; }
#define funcA( a, ... ) funcA( a, ##__VA_ARGS__, 8 )
int funcB( int a, int b ){
if( b == -1 ) b = 8;
return a+b;
}
int main(void){
printf("funcA(1,2): %i\n", funcA(1,2) );
printf("funcA(1): %i\n", funcA(1) );
printf("funcB(1, 2): %i\n", funcB(1, 2) );
printf("funcB(1,-1): %i\n", funcB(1,-1) );
}
还有一个选项使用结构体:
struct func_opts {
int arg1;
char * arg2;
int arg3;
};
void func(int arg, struct func_opts *opts)
{
int arg1 = 0, arg3 = 0;
char *arg2 = "Default";
if(opts)
{
if(opts->arg1)
arg1 = opts->arg1;
if(opts->arg2)
arg2 = opts->arg2;
if(opts->arg3)
arg3 = opts->arg3;
}
// do stuff
}
// call with defaults
func(3, NULL);
// also call with defaults
struct func_opts opts = {0};
func(3, &opts);
// set some arguments
opts.arg3 = 3;
opts.arg2 = "Yes";
func(3, &opts);
你不需要只在c上使用VARARGS,下面是一个例子。
int funcA_12(int a1, int a2) { ... }
#define funcA(a1) funcA_12(a1, 0)
这个答案与上面的两个函数方法非常相似,但在这种情况下,您使用的是定义参数的函数名宏。