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

前端 未结 9 1963
再見小時候
再見小時候 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:13

    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.

    0 讨论(0)
  • 2020-12-09 10:18

    i think u can use a function with variable arguments here is my example

    #include <stdarg.h>
    #include <stdio.h>
    void baz( int flag, ... )
    {
        va_list ap;
        char *bar = "baz"; /* default value */
        va_start( ap, flag );
        if ( flag == 1 )
            bar = va_arg( ap, char * );
        va_end( ap );
        printf( "%s\n", bar );
    }
    int main( void )
    {
        baz( 0 );
        baz( 1, "foo");
        baz( 2 );
        baz( 1, "bar");
        return 0;
    }
    

    the output is

    baz
    foo
    baz
    bar
    

    if u look for example man 2 open they say

    SYNOPSIS
           #include <sys/types.h>
           #include <sys/stat.h>
           #include <fcntl.h>
    
           int open(const char *pathname, int flags);
           int open(const char *pathname, int flags, mode_t mode);
    
           int creat(const char *pathname, mode_t mode);
    
           int openat(int dirfd, const char *pathname, int flags);
           int openat(int dirfd, const char *pathname, int flags, mode_t mode);
    

    but mode is actually a ... argument

    0 讨论(0)
  • 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;
      }
    }
    
    0 讨论(0)
提交回复
热议问题