Page 1 of 1

varargs -> stdarg

Posted: Fri Nov 17, 2023 8:31 am
by imiller
As the C compiler release notes strongly recommends using stdarg instead of varargs then I thought I should have a look at my code that uses varargs.

Consider the following utility function that I use in several of my programs.
Any thoughts on how to change it to use stdarg?

Code: Select all

void
putmsg(ccode,va_alist)
unsigned long ccode;
va_dcl
{
        unsigned long args[20], *argp;
        va_list ap;
        int nargs;
        unsigned short fac;

        fac = $VMS_STATUS_FAC_NO(ccode);
        va_start(ap);
        va_count(nargs);
        args[0] = nargs--;
        args[1] = ccode;


        if (fac == SYSTEM$_FACILITY || fac == RMS$_FACILITY)
                argp = &args[2];
        else
        {
                args[2] = nargs;
                argp = &args[3];
        }

        while (nargs-- > 0)
                *argp++ = va_arg(ap,unsigned long);

        va_end(ap);

        SYS$PUTMSG(args,(void(*)())put_output,0,0);
}

Re: varargs -> stdarg

Posted: Fri Nov 17, 2023 9:03 am
by arne_v
I created these two examples a few months ago:

old:

Code: Select all

#include <stdio.h>
#include <varargs.h>

void test(n, va_alist)
int n;
va_dcl
{
    int i;
    va_list ap;
    va_start(ap);
    for(i = 0; i < n; i++)
    {
       printf("%d : %s\n", i, va_arg(ap, char *));
    }
    va_end(ap);
}

int main(int argc, char *argv[])
{
    test(1, "A");
    test(2, "A", "BB");
    test(3, "A", "BB", "CCC");
    return 0;
}
new:

Code: Select all

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

void test(int n, ...)
{
    int i;
    va_list ap;
    va_start(ap, n);
    for(i = 0; i < n; i++)
    {
       printf("%d : %s\n", i, va_arg(ap, char *));
    }
    va_end(ap);
}

int main(int argc, char *argv[])
{
    test(1, "A");
    test(2, "A", "BB");
    test(3, "A", "BB", "CCC");
    return 0;
}
Added in 2 minutes 25 seconds:
Totally different function declaration and an extra arg to va_start.

Re: varargs -> stdarg

Posted: Fri Nov 17, 2023 9:20 am
by imiller
thanks. I've been RTFM for C and $PUTMSG. I will have to alter the routine putmsg to have a condition value, argument count and optional arguments. I see $PUTMSG supports 64 bit message vectors but I don't think I will have to deal with them.

Re: varargs -> stdarg

Posted: Fri Nov 24, 2023 10:57 am
by imiller
so rewriting this to use stdarg and generalizing it turned out to be a rabbit hole but it is done now.