Passing va_list to other functions

后端 未结 1 1637
名媛妹妹
名媛妹妹 2021-02-07 23:51

I have been trying to pass variable arguments to other function in C but it is producing inconsistent result in different runtime environment as well as in different runs in sam

1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-08 00:19

    You cannot pass the variadic arguments to a variadic function. Instead, you must call a function that takes a va_list as argument. The standard library provides variants of printf and scanf that take a va_list; their names have the prefix v.

    Your example should look like:

    #include 
    #include 
    #include 
    #include 
    
    int printfln(const char *format, ...)
    {
        int result;
        va_list args;
    
        va_start(args, format);
        result = vprintf(format, args);
        printf("\n");
        va_end(args);
    
        return result;
    }
    
    int main()
    {
        int result = printfln("Something \n %d", 9);
    
        printf("(%d)\n", result);
    
        return 0;
    }
    

    There are some gotchas, for example when you want to call two v... function for printing to the screen and a log file: The v... function may exhaust the va_list, so you must pass in a fresh one to each call if your code should be portable.

    0 讨论(0)
提交回复
热议问题