有没有一种方法可以在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));
如果用户不知道他应该写什么,这个技巧会很有用:
其他回答
还有一个选项使用结构体:
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);
为什么我们不能这样做呢?
给可选参数一个默认值。这样,函数的调用者就不一定需要传递实参的值。参数接受默认值。 很容易,这个参数对客户端来说是可选的。
如。
Void foo(int a, int b = 0);
这里b是可选参数。
No.
即使是最新的C99标准也不支持这一点。
是的。:-)但不是你所期望的那样。
int f1(int arg1, double arg2, char* name, char *opt);
int f2(int arg1, double arg2, char* name)
{
return f1(arg1, arg2, name, "Some option");
}
不幸的是,C不允许重载方法,因此最终会得到两个不同的函数。尽管如此,通过调用f2,你实际上是在用默认值调用f1。这是一个“不要重复自己”的解决方案,它可以帮助您避免复制/粘贴现有代码。
使用宏的另一个技巧:
#include <stdio.h>
#define func(...) FUNC(__VA_ARGS__, 15, 0)
#define FUNC(a, b, ...) func(a, b)
int (func)(int a, int b)
{
return a + b;
}
int main(void)
{
printf("%d\n", func(1));
printf("%d\n", func(1, 2));
return 0;
}
如果只传递一个参数,则b接收默认值(在本例中为15)
推荐文章
- C多行宏:do/while(0) vs作用域块
- time_t最终的类型定义是什么?
- 我需要显式处理负数或零时,总和平方数字?
- 函数名周围的括号是什么意思?
- 用C语言创建自己的头文件
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- main()中的Return语句vs exit()
- 如果不是内存地址,C指针到底是什么?
- 我如何在Visual Studio中预处理后看到C/ c++源文件?
- 保护可执行文件不受逆向工程的影响?
- 从C语言的函数返回一个struct
- 如何在IntelliJ IDEA中输入命令行参数?
- C99 'restrict'关键字的实际用法?
- 检查子字符串存在于C中的字符串中
- 从标准输入中捕获字符,而不需要等待按enter键