Default values on arguments in C functions and function overloading in C

前端 未结 9 2056
再見小時候
再見小時候 2020-12-09 09:46

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

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 10:19

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

提交回复
热议问题