Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through a va_list if the number of arguments is unknown?

Tags:

c

How do I loop through a va_list if the number of additional arguments is unknown?

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

int add(int x, int y, ...) {
    va_list intargs;
    int temp = 0;

    va_start(intargs, y);
    int i;
    for (i = 0; i < 3; i++) { /* How can I loop through any number of args? */ 
        temp += va_arg(intargs, int);
    }
    va_end(intargs);

    return temp + x + y;
}

int main() {
    printf("The total is %d.\n", add(1, 2, 3, 4, 5));
    return 0;
}
like image 471
Bob Avatar asked Jan 26 '11 01:01

Bob


2 Answers

You must indicate the number of parameters somehow (if you're writing portable code) when using variable length argument lists. You may be now thinking "But printf doesn't require you to indicate a number of arguments!"

True, however the number can be inferred by first parsing the format strings for % format specifiers.

like image 71
Jason LeBrun Avatar answered Sep 23 '22 12:09

Jason LeBrun


Use a sentinel value as a terminator, e.g NULL or -1

like image 25
Hasturkun Avatar answered Sep 21 '22 12:09

Hasturkun