10

I have some code that looks like this:

uint8_t activities[8];
uint8_t numActivities = 0;
...
activities[numActivities++] = someValue;
...
activities[numActivities++] = someOtherValue;
...
switch (numActivities)
{
   0 : break;
   1 : LogEvent(1, activities[0]);  break;
   2 : LogEvent(1, activities[0], activities[1]);  break;
   3 : LogEvent(1, activities[0], activities[1], activities[2]);  break;
   // and so on
}

where LogEvent() is a varargs function.

Is there a more elgant way to do this?


[Update] Aplogies to @0x69 et al. I omitted to say that there are many cases where LogEvent() could not take an array as a parameter. Sorry.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
Mawg says reinstate Monica
  • 38,334
  • 103
  • 306
  • 551

2 Answers2

3

There's no standard way to construct or manipulate va_args arguments, or even pass them to another function (Standard way to manipulate variadic arguments?, C Programming: Forward variable argument list). You'd be better off seeing if you can access the internal routines of LogEvent.

Community
  • 1
  • 1
ecatmur
  • 152,476
  • 27
  • 293
  • 366
2

pass a pointer to the array of ints and a number of ints instead

#include <stdio.h>

void logevent(int n, int num, int *l) {
    int i;
    for (i=0; i<num; i++) {
        printf("%d %d\n",n,*(l++));
    }
    }

int main() {

    int activities[8];
    activities[0]=2;
    activities[1]=3;
    activities[2]=4;
    int num=3;
    int n=1;
    logevent(n,num, activities);
    printf("=========\n");
    n=2;
    activities[3]=5;
    num=4;
    logevent(n,num, activities);

}
Vorsprung
  • 32,923
  • 5
  • 39
  • 63