Optional arguments in C function

后端 未结 3 918
小鲜肉
小鲜肉 2021-02-08 02:44

In a C function, I want to check if an input argument (\'value\' in my case) is presented or not.

i.e.:

void Console(char string[], int32_t value)
{
             


        
3条回答
  •  清酒与你
    2021-02-08 03:28

    If you want to distinguish between function calls that take either one or two arguments, you can use macros.

    While you can reproduce your desired behaviour, there are some things to note:

    • The macro implentation hides the overloading to casual readers of your code who can't see that Console is a macro. C is much about seeing the details, so if you have two different functions, they should probably get different names, maybe cons_str and cons_str_int.

    • The macro will generate a compiler error if you pass more than two arguments or if the arguments are not compatible with the required types C string and int. Which is actually a good thing.

    • Real variadic functions like printf that use the interface from must be able to derive the types and number of variadic arguments. In printf, this is done via the % format specifiers. The macro can switch between different implementations based on the number of arguments alone.

    Anyway, here's an implementation. Proceed with caution.

    #include 
    #include 
    
    #define NARGS(...) NARGS_(__VA_ARGS__, 5, 4, 3, 2, 1, 0)
    #define NARGS_(_5, _4, _3, _2, _1, N, ...) N
    
    #define CONC(A, B) CONC_(A, B)
    #define CONC_(A, B) A##B
    
    #define Console(...) CONC(Console, NARGS(__VA_ARGS__))(__VA_ARGS__)
    
    
    
    void Console1(const char string[])
    {
        printf("%s\n", string);
    }
    
    void Console2(const char string[], int32_t value)
    {
        printf("%s: %d\n", string, value);
    }
    
    int main()
    {
        Console("Hello");
        Console("Today's number is", 712);
    
        return 0;
    }
    

提交回复
热议问题