Default values on arguments in C functions and fun

2019-01-17 21:31发布

Converting a C++ lib to ANSI C and it seems like though ANSI C doesn't support default values for function variables or am I mistaken? What I want is something like

int funcName(int foo, bar* = NULL);

Also, is function overloading possible in ANSI C?

Would need

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

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

Could of course just name them differently but being used to C++ I kinda used to function overloading.

9条回答
Fickle 薄情
2楼-- · 2019-01-17 22:35

As far as I know ANSI C doesn't directly support function overloading or default arguments. The standard substitute for overloading is adding suffixes to the function name indicating the argument types. For example, in OpenGL, a "3fv" suffix to a function name means the function takes a vector of three floats.

Default arguments can be viewed as a special case of function overloading.

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-17 22:36

There is a way to support as many default parameters you need, just use a structure.

// 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;
  }
}
查看更多
【Aperson】
4楼-- · 2019-01-17 22:37

No, Standard C does not support either. Why do you feel you need to convert your C++ code to C? That could get quite tricky - I'd have thought writing wrappers would be the way to go, if your C++ must be callable from C.

查看更多
登录 后发表回答