-1

Possible Duplicate:
C/C++: Passing variable number of arguments around

How can I do a function that has a variable number of arguments. For example:

      typedef enum{
              Circle, /* has an int argument (int colour)*/
              Square /* has a char argument (char name)*/
      }things;

      /* if arg is a ball I want an int (with colour) argument in f*/
      /* if arg is a square I want a char (with name) argument in f*/
      void f (things arg, ...){
      }

Is this possible to do in the same function f? Thanks

Community
  • 1
  • 1
tomss
  • 269
  • 4
  • 6
  • 12
  • Have you checked this:- http://stackoverflow.com/questions/205529/c-c-passing-variable-number-of-arguments-around ? – Rahul Tripathi Dec 01 '12 at 08:37
  • @Zeta That question is about passing variable arguments to another function, not how to get variable arguments in the first place. – Barmar Dec 01 '12 at 09:15

2 Answers2

0

Yes. Here is a example of how it is done.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0

Here is an example it is done, which finds the max of a variable number of numbers.

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

int maxof(int, ...) ;
void f(void);

main(){
        f();
        exit(EXIT SUCCESS);
}

int maxof(int n args, ...){
        register int i;
        int max, a;
        va_list ap;

        va_start(ap, n args);
        max = va_arg(ap, int);
        for(i = 2; i <= n_args; i++) {
                if((a = va_arg(ap, int)) > max)
                        max = a;
        }

        va_end(ap);
        return max;
}

void f(void) {
        int i = 5;
        int j[256];
        j[42] = 24;
        printf("%d\n",maxof(3, i, j[42], 0));
}
0x90
  • 39,472
  • 36
  • 165
  • 245