Victor Brunell
Victor Brunell

Reputation: 6448

C: Accessing the ith vararg

I've searched for the proper syntax to access the ith variable argument in C to no avail. Is this possible? I'd like to access, say, the 2nd argument in a variable argument list.

For example:

void mySum( int count, ... )
{
    int sum = 0;
    va_list args;
    va_start(args, count);
    for( int i = 0; i < count; i++ )
    {
        sum += va_arg(args, int);
    }

    printf("%d\n", sum );
 }

This accesses each variable argument in turn. Is there a way to reference the second variable argument directly, or do you have to call va_arg() at least once first?

Upvotes: 2

Views: 82

Answers (2)

John Bode
John Bode

Reputation: 123588

There's no (good, safe, portable) way to randomly access arguments in a variable argument list. If you know exactly how variable argument lists are implemented on your particular platform, you could try to work around the standard va_* macros; otherwise, you're stuck with iterating through the list until you reach the argument you want.

Upvotes: 3

MK.
MK.

Reputation: 34597

You can't access them randomly because the arguments are stored in stack and you need to know the sizes of all preceding arguments to access a particular one.

Upvotes: -1

Related Questions