close
Namespaces
Variants

Talk:c/variadic/va list

From cppreference.com

Example

I have been seeking a suitable example for this page. I would like the example to be different from the examples on related pages of stdarg.h by showing how to use footnote 253 of n1570 (pass-by-pointer to avoid UB). I would like it to exhibit continuous parsing, so each call to a function must see the effect of the previous call. I am concerned that the example be portable, so I have been reading about how the unspecified va_list can be an array type in one architecture (x86-64 ABI) and possibly not an array type in another architecture. I would like the example to show that more than one function can access the variable arguments and that those functions can be called more than once. Here is the example. It works at Coliru (-xc -std=c11). What do you think? Is it suitable? If not, how should I change it?

#include <stdio.h>
#include <stdarg.h>

void bar1(va_list *ap)  /* pointer to va_list */
{
    int value = va_arg(*ap,int);
    /* some int work here */
    printf("%d\n", value);
}

void bar2(va_list *ap)
{
    double value = va_arg(*ap,double);
    /* some double work here */
    printf("%.1f\n", value);
}

void foo(int count,...)
{
    va_list ap;
    va_start(ap,count);
    for (int i=0;i<count/2;++i)
        bar1(&ap);   /* address of ap (pass-by-pointer, not by-value) */
    for (int i=0;i<count/2;++i)
        bar2(&ap);
    va_end(ap);
}

int main(void)
{
    foo(4,1,2,3.3,4.4);
    return 0;
}

Newatthis (talk) 14:22, 26 June 2014 (PDT)

I feel that the description given on the page is sufficient, although a realistic example showing the technique alluded to by the standard would be nice. I actually couldn't remember having to use this at all, so I checked the codebase I work with: there are 9189 files that use va_list and I found a case where it's passed by pointer after checking a little over a hundred non-passing and pass-by-value cases. So, my preference would be for the more common usage. Incidentally, please don't write redundant comments like "address of ap" or "pointer to va_list": this isn't a page that explains what * or & mean. --Cubbi (talk) 19:54, 26 June 2014 (PDT)
I am seeking a realistic example to replace my toy example. Newatthis (talk) 06:14, 28 June 2014 (PDT)
I run into this with an implementation of the printf family of functions where parsing a format specifier and extracting the va_arg is delegated to a helper function. 46.5.255.82 11:07, 13 February 2022 (PST)