Reputation: 596
I have a function in C, which takes a bunch of arguments, and I would like to treat those arguments like an array and access them by number. For example, say I want to take 6 arguments plus a parameter from 1 to 6, and increment the corresponding argument. I could do:
void myFunc(int arg1,int arg2,int arg3,int arg4,int arg5,int arg6,n)
{
if (n==1) ++arg1;
else if (n==2) ++arg2;
else if (n==3) ++arg3;
else if (n==4) ++arg4;
else if (n==5) ++arg5;
else if (n==6) ++arg6;
}
But that's a bit messy. Is there a neater way to do this?
Upvotes: 2
Views: 178
Reputation: 3660
Pass your arguments in as an array. Here I just used literals, but you could replace 1,2,3,4
with your own variables like arg1, arg2
, and so on.
int myNumbers[] = { 1, 2, 3, 4 };
myFunc(myNumbers, sizeof myNumbers / sizeof myNumbers[0]);
Then, your function needs to be prepared to accept the array. Also, rather than using six if's to check six arguments, we can write a for loop. However, that is entirely unrelated to the question and I understand you may be doing this for a class assignment.
void myFunc(int *args, int numArgs)
{
int i = 0;
for(i; i < numArgs; i++)
{
if(args[i] == i+1) ++args[i];
}
}
Upvotes: 1
Reputation: 64682
I'd do it like this:
void myFunc(int n, ...)
{
va_list args;
va_start(args, n);
int temp;
for(n; n; --n)
{
temp = va_arg(vl, int);
}
temp++;
va_end(args);
}
A few things to note:
Upvotes: 4
Reputation: 22542
Although as suggested in the comments passing a pointer to an array may be easier. If you really want to go with arguments then your best bet may be to use a variadric function:
void myFunc(int n, ...)
{
va_list ap;
int arg;
va_start(ap, n);
while (--n)
arg = va_arg(ap, int); /* Increments ap to the next argument. */
va_end(ap);
arg++;
}
Upvotes: 6
Reputation: 28261
You can use a temporary array of pointers to your arguments, then you can access them through this array of pointers:
void myFunc(int arg1,int arg2,int arg3,int arg4,int arg5,int arg6,n)
{
int *array_of_args[] = {&arg1, &arg2, &arg3, &arg4, &arg5, &arg6};
if (n >= 1 && n <= 6)
++*array_of_args[n - 1];
}
This is not better than your original code, but if your code uses the array-access several times, this hack will make the code smaller.
Upvotes: 2