#Variadic argument usage (C99)

1 messages · Page 1 of 1 (latest)

wispy spade
#

I wish to implement the following functionality:

int main() {
    struct LeBigInt *x, *multiplicand, *addend;

    /* Pointers are allocated and used here */

    lbi_free(x, multiplicand, addend, result);
}

Looking at the varargs example on cppreference:

#include <stdio.h>
#include <stdarg.h>
 
int add_nums_C99(int count, ...)
{
    int result = 0;
    va_list args;
    va_start(args, count); // count can be omitted since C23
 
    for (int i = 0; i < count; ++i) {
        result += va_arg(args, int);
    }
 
    va_end(args);
    return result;
}
 
int main(void)
{
    printf("%d\n", add_nums_C99(4, 25, 25, 50, 50));
}

I'm having trouble figuring out how to use the va_* functions provided to write a function that does not require passing in the number of arguments as the first argument.

solemn vineBOT
#

When your question is answered use !solved or the button below to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

proper hinge
#

the whole point of variadic arguments is that the number of arguments is sorta unknown

#

you have to deduce it from the input somehow (e.g. for printf it just calls va_arg for every format specifier)

pseudo sundial
proper hinge
#

i saw some cursed variadic macro abuse to count arguments somewhere but its probably not ideal

pseudo sundial
#

yeah I was gonna suggest that

#

@wispy spade
I think this might help you

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

#define add_nums(...) \
    _add_nums_C99(sizeof((int[]){__VA_ARGS__})/sizeof(int), __VA_ARGS__)

int _add_nums_C99(int count, ...)
{
    int result = 0;
    va_list args;
    va_start(args, count); // count can be omitted since C23, btw
 
    for (int i = 0; i < count; ++i) {
        result += va_arg(args, int);
    }
 
    va_end(args);
    return result;
}
 
int main(void)
{
    printf("%d\n", add_nums(25, 25, 50, 50));
}
#

you need to keep in mind that the argument that you're gonna pass to add_nums macros have to known at compile time

proper hinge
#

so not sure if that's gonna work

pseudo sundial
#

only if those pointers they are going to pass is is known at compile time

#

like just how many of them

wispy spade
#

Intriguing trick, thanks for the help

#

Though for the sake of clarity I've decided to just free the pointers one by one

#

instead of trying to be clever