How to use a function with dynamic number of argument until zero with va_arg() in C

1 Answer

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

void PrintNumbers(int startnum, ...) {
    int count = 0;
    int n = startnum;
    
    va_list vl;
    va_start(vl, startnum);

    while (n != 0) {
        printf("%d\n", n);
        n = va_arg(vl, int);
    }

    va_end(vl);
}

int main(void)
{
    PrintNumbers(1, 2, 3, 4, 5, 0);

    return 0;
}



/*
run:

1
2
3
4
5

*/

 



answered Apr 21, 2016 by avibootz
edited Apr 26, 2024 by avibootz

Related questions

1 answer 146 views
1 answer 95 views
95 views asked Apr 23, 2022 by avibootz
2 answers 281 views
...