328

有没有办法在 C 中为函数指定默认参数?

4

22 回答 22

326

哇,这里的每个人都是如此悲观的人。答案是肯定的。

这不是微不足道的:到最后,我们将拥有核心函数、支持结构、包装函数和围绕包装函数的宏。在我的工作中,我有一组宏来自动化这一切;一旦你了解了流程,你就很容易做到这一点。

我已经在其他地方写了这个,所以这里有一个详细的外部链接来补充这里的摘要:http: //modelingwithdata.org/arch/00000022.htm

我们想转

double f(int i, double x)

进入一个采用默认值的函数(i = 8,x = 3.14)。定义一个伴随结构:

typedef struct {
    int i;
    double x;
} f_args;

重命名你的函数f_base,并定义一个设置默认值并调用基础的包装函数:

double var_f(f_args in){
    int i_out = in.i ? in.i : 8;
    double x_out = in.x ? in.x : 3.14;
    return f_base(i_out, x_out);
}

现在添加一个宏,使用 C 的可变参数宏。这样用户就不必知道他们实际上是在填充一个f_args结构并认为他们在做通常的事情:

#define f(...) var_f((f_args){__VA_ARGS__});

好的,现在以下所有方法都可以工作:

f(3, 8);      //i=3, x=8
f(.i=1, 2.3); //i=1, x=2.3
f(2);         //i=2, x=3.14
f(.x=9.2);    //i=8, x=9.2

检查有关复合初始值设定项如何为确切规则设置默认值的规则。

一件事不起作用:f(0),因为我们无法区分缺失值和零。根据我的经验,这是需要注意的事情,但可以在需要时加以注意——你的默认值实际上是零的一半时间。

我写这篇文章时遇到了麻烦,因为我认为命名参数和默认值确实使 C 中的编码更容易,甚至更有趣。C 语言非常简单,而且仍然有足够的能力使这一切成为可能。

于 2010-05-28T01:39:13.853 回答
174

是的。:-) 但不是以你期望的方式。

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。这是一个“不要重复自己”的解决方案,它可以帮助您避免复制/粘贴现有​​代码。

于 2009-09-24T15:06:55.427 回答
166

并不真地。唯一的方法是编写一个可变参数函数并手动填写调用者未传递的参数的默认值。

于 2009-09-24T14:40:20.227 回答
44

我们可以创建将命名参数(仅)用于默认值的函数。这是bk.的答案的延续。

#include <stdio.h>                                                               

struct range { int from; int to; int step; };
#define range(...) range((struct range){.from=1,.to=10,.step=1, __VA_ARGS__})   

/* use parentheses to avoid macro subst */             
void (range)(struct range r) {                                                     
    for (int i = r.from; i <= r.to; i += r.step)                                 
        printf("%d ", i);                                                        
    puts("");                                                                    
}                                                                                

int main() {                                                                     
    range();                                                                    
    range(.from=2, .to=4);                                                      
    range(.step=2);                                                             
}    

C99 标准定义了初始化中后面的名称会覆盖前面的项目。我们也可以有一些标准的位置参数,只需相应地更改宏和函数签名。默认值参数只能用于命名参数样式。

程序输出:

1 2 3 4 5 6 7 8 9 10 
2 3 4 
1 3 5 7 9
于 2011-10-29T05:14:36.170 回答
25

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

如果用户不知道他应该写什么,这个技巧会很有帮助:

使用示例

于 2012-12-18T19:38:53.383 回答
18

不,这是 C++ 语言功能。

于 2009-09-24T14:39:41.883 回答
18

不。

甚至最新的 C99 标准也不支持这一点。

于 2009-09-24T14:39:58.777 回答
16

可能最好的方法(根据您的情况,在您的情况下可能会或可能不会)是迁移到 C++ 并将其用作“更好的 C”。您可以在不使用类、模板、运算符重载或其他高级特性的情况下使用 C++。

这将为您提供具有函数重载和默认参数(以及您选择使用的任何其他功能)的 C 变体。如果你真的很想只使用 C++ 的受限子集,那么你只需要有点自律。

很多人会说以这种方式使用 C++ 是一个糟糕的主意,他们可能说得有道理。但这只是一种意见;我认为使用你熟悉的 C++ 特性是有效的,而不必购买整个东西。我认为 C++ 成功的一个重要原因是它在早期就以这种方式被大量程序员使用。

于 2009-09-24T18:14:31.413 回答
15

简短的回答:没有。

稍微长一点的答案:有一个旧的、旧的解决方法,您可以传递一个为可选参数解析的字符串:

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)编写的粒子物理代码中找到这种方法。它的主要优点是它可以几乎无限期地扩展,同时保持向后兼容性。

于 2009-09-24T14:39:47.840 回答
15

还有一个选项使用structs:

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);
于 2009-09-24T19:49:10.337 回答
13

使用宏的另一个技巧:

#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)

于 2018-10-02T14:12:28.917 回答
10

不。

于 2009-09-24T15:01:20.723 回答
5

是的,使用 C99 的功能,您可以做到这一点。这无需定义新的数据结构,也无需函数在运行时决定如何调用它,也无需任何计算开销。

有关详细说明,请参阅我的帖子

http://gustedt.wordpress.com/2010/06/03/default-arguments-for-c99/

延斯

于 2010-06-14T13:56:33.833 回答
4

不,但您可以考虑使用一函数(或宏)来近似使用默认参数:

// 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
}
于 2009-09-24T16:32:43.637 回答
4

我改进了 Jens Gustedt 的回答,以便:

  1. 不使用内联函数
  2. 默认值是在预处理期间计算的
  3. 模块化可重用宏
  4. 可以设置与允许默认值的参数不足的情况有意义匹配的编译器错误
  5. 如果参数类型保持明确,则不需要默认值来形成参数列表的尾部
  6. 与 C11 _Generic 互用
  7. 通过参数数量改变函数名称!

可变参数.h:

#ifndef VARIADIC

#define _NARG2(_0, _1, _2, ...) _2
#define NUMARG2(...) _NARG2(__VA_ARGS__, 2, 1, 0)
#define _NARG3(_0, _1, _2, _3, ...) _3
#define NUMARG3(...) _NARG3(__VA_ARGS__, 3, 2, 1, 0)
#define _NARG4(_0, _1, _2, _3, _4, ...) _4
#define NUMARG4(...) _NARG4(__VA_ARGS__, 4, 3, 2, 1, 0)
#define _NARG5(_0, _1, _2, _3, _4, _5, ...) _5
#define NUMARG5(...) _NARG5(__VA_ARGS__, 5, 4, 3, 2, 1, 0)
#define _NARG6(_0, _1, _2, _3, _4, _5, _6, ...) _6
#define NUMARG6(...) _NARG6(__VA_ARGS__, 6, 5, 4, 3, 2, 1, 0)
#define _NARG7(_0, _1, _2, _3, _4, _5, _6, _7, ...) _7
#define NUMARG7(...) _NARG7(__VA_ARGS__, 7, 6, 5, 4, 3, 2, 1, 0)
#define _NARG8(_0, _1, _2, _3, _4, _5, _6, _7, _8, ...) _8
#define NUMARG8(...) _NARG8(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define _NARG9(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, ...) _9
#define NUMARG9(...) _NARG9(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define __VARIADIC(name, num_args, ...) name ## _ ## num_args (__VA_ARGS__)
#define _VARIADIC(name, num_args, ...) name (__VARIADIC(name, num_args, __VA_ARGS__))
#define VARIADIC(name, num_args, ...) _VARIADIC(name, num_args, __VA_ARGS__)
#define VARIADIC2(name, num_args, ...) __VARIADIC(name, num_args, __VA_ARGS__)

// Vary function name by number of arguments supplied
#define VARIADIC_NAME(name, num_args) name ## _ ## num_args ## _name ()
#define NVARIADIC(name, num_args, ...) _VARIADIC(VARIADIC_NAME(name, num_args), num_args, __VA_ARGS__)

#endif

简化使用场景:

const uint32*
uint32_frombytes(uint32* out, const uint8* in, size_t bytes);

/*
The output buffer defaults to NULL if not provided.
*/

#include "variadic.h"

#define uint32_frombytes_2(   b, c) NULL, b, c
#define uint32_frombytes_3(a, b, c)    a, b, c
#define uint32_frombytes(...) VARIADIC(uint32_frombytes, NUMARG3(__VA_ARGS__), __VA_ARGS__)

并使用 _Generic:

const uint8*
uint16_tobytes(const uint16* in, uint8* out, size_t bytes);

const uint16*
uint16_frombytes(uint16* out, const uint8* in, size_t bytes);

const uint8*
uint32_tobytes(const uint32* in, uint8* out, size_t bytes);

const uint32*
uint32_frombytes(uint32* out, const uint8* in, size_t bytes);

/*
The output buffer defaults to NULL if not provided.
Generic function name supported on the non-uint8 type, except where said type
is unavailable because the argument for output buffer was not provided.
*/

#include "variadic.h"

#define   uint16_tobytes_2(a,    c) a, NULL, c
#define   uint16_tobytes_3(a, b, c) a,    b, c
#define   uint16_tobytes(...) VARIADIC(  uint16_tobytes, NUMARG3(__VA_ARGS__), __VA_ARGS__)

#define uint16_frombytes_2(   b, c) NULL, b, c
#define uint16_frombytes_3(a, b, c)    a, b, c
#define uint16_frombytes(...) VARIADIC(uint16_frombytes, NUMARG3(__VA_ARGS__), __VA_ARGS__)

#define   uint32_tobytes_2(a,    c) a, NULL, c
#define   uint32_tobytes_3(a, b, c) a,    b, c
#define   uint32_tobytes(...) VARIADIC(  uint32_tobytes, NUMARG3(__VA_ARGS__), __VA_ARGS__)

#define uint32_frombytes_2(   b, c) NULL, b, c
#define uint32_frombytes_3(a, b, c)    a, b, c
#define uint32_frombytes(...) VARIADIC(uint32_frombytes, NUMARG3(__VA_ARGS__), __VA_ARGS__)

#define   tobytes(a, ...) _Generic((a),                                                                                                 \
                                   const uint16*: uint16_tobytes,                                                                       \
                                   const uint32*: uint32_tobytes)  (VARIADIC2(  uint32_tobytes, NUMARG3(a, __VA_ARGS__), a, __VA_ARGS__))

#define frombytes(a, ...) _Generic((a),                                                                                                 \
                                         uint16*: uint16_frombytes,                                                                     \
                                         uint32*: uint32_frombytes)(VARIADIC2(uint32_frombytes, NUMARG3(a, __VA_ARGS__), a, __VA_ARGS__))

并且使用不能与 _Generic 结合的可变函数名称选择:

// winternitz() with 5 arguments is replaced with merkle_lamport() on those 5 arguments.

#define   merkle_lamport_5(a, b, c, d, e) a, b, c, d, e
#define   winternitz_7(a, b, c, d, e, f, g) a, b, c, d, e, f, g
#define   winternitz_5_name() merkle_lamport
#define   winternitz_7_name() winternitz
#define   winternitz(...) NVARIADIC(winternitz, NUMARG7(__VA_ARGS__), __VA_ARGS__)
于 2015-11-18T17:51:30.140 回答
3

一般不会,但在 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) );
}
于 2009-09-24T16:48:00.280 回答
2

是的

通过宏

3 参数:

#define my_func2(...) my_func3(__VA_ARGS__, 0.5)
#define my_func1(...) my_func2(__VA_ARGS__, 10)
#define VAR_FUNC(_1, _2, _3, NAME, ...) NAME
#define my_func(...) VAR_FUNC(__VA_ARGS__, my_func3, my_func2, my_func1)(__VA_ARGS__)

void my_func3(char a, int b, float c) // b=10, c=0.5
{
    printf("a=%c; b=%d; c=%f\n", a, b, c);
}

如果您想要第 4 个参数,则需要添加一个额外的 my_func3 。注意 VAR_FUNC、my_func2 和 my_func 的变化

4个参数:

#define my_func3(...) my_func4(__VA_ARGS__, "default") // <== New function added
#define my_func2(...) my_func3(__VA_ARGS__, (float)1/2)
#define my_func1(...) my_func2(__VA_ARGS__, 10)
#define VAR_FUNC(_1, _2, _3, _4, NAME, ...) NAME
#define my_func(...) VAR_FUNC(__VA_ARGS__, my_func4, my_func3, my_func2, my_func1)(__VA_ARGS__)

void my_func4(char a, int b, float c, const char* d) // b=10, c=0.5, d="default"
{
    printf("a=%c; b=%d; c=%f; d=%s\n", a, b, c, d);
}

唯一的例外是浮点变量不能被赋予默认值(除非它是最后一个参数,如 3 个参数的情况),因为它们需要句点('.'),宏参数中不接受它。但可以找出一个解决方法,如 my_func2 宏中所见(4 个参数案例

程序

int main(void)
{
    my_func('a');
    my_func('b', 20);
    my_func('c', 200, 10.5);
    my_func('d', 2000, 100.5, "hello");

    return 0;
}

输出:

a=a; b=10; c=0.500000; d=default                                                                                                                                                  
a=b; b=20; c=0.500000; d=default                                                                                                                                                  
a=c; b=200; c=10.500000; d=default                                                                                                                                                
a=d; b=2000; c=100.500000; d=hello  
于 2018-07-23T08:06:54.800 回答
0

是的,你可以做一些类似的事情,在这里你必须知道你可以获得的不同参数列表,但你有相同的功能来处理所有的事情。

typedef enum { my_input_set1 = 0, my_input_set2, my_input_set3} INPUT_SET;

typedef struct{
    INPUT_SET type;
    char* text;
} input_set1;

typedef struct{
    INPUT_SET type;
    char* text;
    int var;
} input_set2;

typedef struct{
    INPUT_SET type;
    int text;
} input_set3;

typedef union
{
    INPUT_SET type;
    input_set1 set1;
    input_set2 set2;
    input_set3 set3;
} MY_INPUT;

void my_func(MY_INPUT input)
{
    switch(input.type)
    {
        case my_input_set1:
        break;
        case my_input_set2:
        break;
        case my_input_set3:
        break;
        default:
        // unknown input
        break;
    }
}
于 2009-09-25T11:02:17.557 回答
0

我知道如何以更好的方式做到这一点。您只需将 NULL 分配给参数,因此您将没有任何价值。然后检查参数值是否为NULL,将其更改为默认值。

void func(int x){
if(x == NULL)
  x = 2;
....
}

但是,它会引起警告。更好的选择是分配一个值,如果参数值为:

void func(int x){
if(x == 1)
  x = 2;
....
}

在上面的例子中, if xis1函数将其更改为2;

感谢@user904963,编辑:如果你必须涵盖所有数字范围,添加另一个参数只是为了告诉函数它是否会将参数设置为默认值并不难

void func(int x, bool useDefault){
if(useDefault) //useDefault == true
  x = 2;
....
}

但是,请记住包括stdbool.h

于 2022-02-23T11:17:51.187 回答
0

https://github.com/cindRoberta/C/blob/master/structure/function/default_parameter.c

#include<stdio.h>

void f_impl(int a, float b) {
  printf("%d %g\n", a, b);
}

#define f_impl(...) f_macro(__VA_ARGS__, 3.7)
#define f_macro(a, b, ...) f_impl(a, b)

int main(void) {
  f_impl(1);
  f_impl(1, 2, 3, 4);

  return 0;
}
于 2021-11-22T16:09:20.290 回答
0

您不需要仅将 VARARGS 与 C 一起使用。这是一个示例。

int funcA_12(int a1, int a2) { ... }

#define funcA(a1) funcA_12(a1, 0)

这个答案与上面的两个函数方法非常相似,但在这种情况下,您使用宏作为定义参数的函数名称。

于 2021-09-02T13:34:19.633 回答
-6

为什么我们不能这样做。

给可选参数一个默认值。这样,函数的调用者不一定需要传递参数的值。该参数采用默认值。并且很容易该参数对于客户来说是可选的。

例如

void foo(int a, int b = 0);

这里 b 是一个可选参数。

于 2013-08-22T11:46:40.327 回答