C语言中参数的默认值和C中的函数重载

inq*_*uam 18 c default overloading function

将C++库转换为ANSI C,似乎ANSI C不支持函数变量的默认值,或者我错了?我想要的是类似的东西

int funcName(int foo, bar* = NULL);
Run Code Online (Sandbox Code Playgroud)

另外,ANSI C中的函数重载是否可行?

需要

const char* foo_property(foo_t* /* this */, int /* property_number*/);

const char* foo_property(foo_t* /* this */, const char* /* key */, int /* iter */);
Run Code Online (Sandbox Code Playgroud)

当然可以用不同的方式命名它们,但是习惯于C++,我曾经习惯于重载.

小智 29

不,标准C也不支持.为什么您认为需要将C++代码转换为C?这可能会变得非常棘手 - 如果您的C++必须可以从C调用,我认为编写包装器是可行的方法.

  • @ inquam:不要.使用手头的语言,不要试图强迫编译器的其他语言.虽然使C代码在C++环境中工作相对容易,但反过来却是微不足道的(正如你刚才意识到的那样).而是将"有用的类"重新实现为C函数库,而不是尝试以1:1"移植"它. (3认同)

小智 22

然而,如果你使用GCC,我发现了一个"技巧".

GCC在variadic宏上有一个方便的##扩展,允许你模拟一个默认参数.

技巧有局限性:它仅适用于1个默认值,参数必须是最后一个函数参数.

这是一个有效的例子.

#include <stdio.h>


#define SUM(a,...) sum( a, (5, ##__VA_ARGS__) )

int sum (a, b)
  int a;
  int b;
{
  return a + b;
}


main()
{

  printf("%d\n", SUM( 3, 7 ) );

  printf("%d\n", SUM( 3 ) );

}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我将SUM定义为对sum的调用,默认的第二个参数为5.

如果使用2个参数(在主首先调用)调用,将它作为prepocessed:总和(3,(5,7));

这意味着:

  • 第一个参数是3
  • 第二个参数是序列(5,7)的结果......显然是7!

由于gcc很聪明,这对运行时没有影响,因为序列的第一个成员是常量而且不需要它,它将在编译时被丢弃.

如果只使用一个参数调用,gcc扩展名将删除VA_ARGS 前导昏迷.所以它被预处理为:

sum(3,(5));

因此该程序给出了预期的输出:

10
8
Run Code Online (Sandbox Code Playgroud)

所以,这并不完全模拟(与通常的宏观限制)功能以2个参数,最后一个是可选的,如果不提供应用的默认值.


小智 6

尝试这个。

#include <stdio.h>
#include <stdarg.h>

/* print all non-negative args one at a time;
   all args are assumed to be of int type */
void printargs(int arg1, ...)
{
  va_list ap;
  int i;

  va_start(ap, arg1); 
  for (i = arg1; i >= 0; i = va_arg(ap, int))
    printf("%d ", i);
  va_end(ap);
  putchar('\n');
}

int main(void)
{
   printargs(5, 2, 14, 84, 97, 15, 24, 48, -1);
   printargs(84, 51, -1);
   printargs(-1);
   printargs(1, -1);
   return

 0;
}
Run Code Online (Sandbox Code Playgroud)


小智 5

有一种方法可以支持所需的许多默认参数,只需使用结构即可。

// Populate structure with var list and set any default values
struct FooVars {
  int int_Var1 = 1;  // One is the default value
  char char_Command[2] = {"+"};
  float float_Var2 = 10.5;
};
struct FooVars MainStruct;

//...
// Switch out any values needed, leave the rest alone
MainStruct.float_Var2 = 22.8;
Myfunc(MainStruct);  // Call the function which at this point will add 1 to 22.8.
//...

void Myfunc( struct FooVars *MyFoo ) {
  switch(MyFoo.char_Command) {
    case '+':
      printf("Result is %i %c %f.1 = %f\n" MyFoo.int_Var1, MyFoo.char_Command, MyFoo.float_Var2, (MyFoo.float_Var2 + MyFoo.int_Var1);
      break;
    case '*':
      // Insert multiply here, you get the point...
      break;
    case '//':
      // Insert divide here...
      break;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我不是C专家,但是您不能在这样的结构中设置默认值。你是否可以? (6认同)