Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access function arguments as an array?

Tags:

c

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?

like image 978
user1837296 Avatar asked Jan 22 '26 09:01

user1837296


1 Answers

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++;

}
like image 112
Sergey L. Avatar answered Jan 24 '26 07:01

Sergey L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!