James Carter
James Carter

Reputation: 387

Argument variables in C

I am writing a method that takes in a number n and n ints(a variable number) and this function will return the sum of the ints not including n. I am stuck on how to access each paramater individually. Here is what I have so far, I read about it online and hopefully I am on the right track. method that seem to be useful found on the net are:

va_start()
va_arg()
va_end()


int sumv(int n, ...)
{
  va_list list;
  int sum = 0;
  while(n>0)
  {
    //*********************
    //this is the part where I am stuck on, how do I get each paramater?
    //I know it will be an int
    //*********************
    n--;
  }
  return sum;
}

Upvotes: 2

Views: 119

Answers (2)

paxdiablo
paxdiablo

Reputation: 881363

You're basically looking for this:

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

int sumv (int n, ...) {
    va_list list;

    int sum = 0;

    va_start (list, n);
    while (n-- > 0)
        sum += va_arg (list, int);
    va_end (list);

    return sum;
}

int main (void) {
    printf ("%d\n", sumv (5, 1, 2, 3, 4, 5));
    return 0;
}

This prints the sum of the first five natural numbers, 15.

The basic idea is to va_start, giving both the list to use and the final argument in the function before the variable arguments begin.

Then, each call to va_arg gives you the next argument of the type specified (int here). This particular code calls it based on your counter but you could equally use a sentinel value at the end such as a negative number, provided that negative numbers aren't valid in the arguments.

Then, once you've processed all the arguments, use va_end to terminate the processing.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490108

It should look something like this:

int sumv(int n, ...)
{
  va_list list;
  va_start(list, n);
  int sum = 0;
  while(n>0)
  {
    sum += va_arg(list, int);
    n--;
  }
  va_end(list);
  return sum;
}

Upvotes: 5

Related Questions