有没有一种方法可以在C语言中指定函数的默认参数?
当前回答
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.
即使是最新的C99标准也不支持这一点。
简单的回答:不。
稍微长一点的回答:有一个很老很老的解决方法,你传递一个字符串来解析可选参数:
int f(int arg1, double arg2, char* name, char *opt);
哪里的opt可能包括“name=value”对或其他东西,你会叫喜欢吗
n = f(2,3.0,"foo","plot=yes save=no");
显然,这只是偶尔有用。一般来说,当你想要一个单一的接口到一系列功能时。
你仍然可以在专业程序用c++编写的粒子物理代码中找到这种方法(例如ROOT)。它的主要优点是可以几乎无限期地扩展,同时保持向后兼容性。
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));
如果用户不知道他应该写什么,这个技巧会很有用:
还有一个选项使用结构体:
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);
我知道如何更好地做到这一点。 您只需将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