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

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

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

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

提交回复
热议问题