C programming – How to Pass Variable List of Arguments to Another Function

CWC
3 Min Read

While introducing a function, the types and number of arguments are typically settled at compile time. Yet, some of the time is important for a function to have the capacity to acknowledge a variable number of arguments obscure until run-time.

This instructional exercise will demonstrate to you industry standards to make a C function that can acknowledge a variable number of arguments.

In A Nutshell

If you’re essentially searching for a case to get off, I won’t keep you holding up. Here’s a case of a function entirety() that includes the greater part of the whole numbers passed to it and returns the aggregate.

Below is how to pass variable list of arguments to another function in c programming

The stdarg library gives us the va_list information sort, and additionally the macros va_start, va_arg, and va_end for controlling the list of arguments.

To proclaim the function, we utilize a triple speck (…) to signify that the function acknowledges a variable number of arguments. The principal contention, num, is utilized to show what number of arguments were passed into the function.

If we would not like to utilize the primary contention as a contention length specifier, we could have basically utilized the main contention as a component of the numbered to be summed up, and afterward utilized some kind of exceptional number (negative one, maybe) as a marker that the last contention has been come to.

Here, we circle through the list of arguments until we’ve perused the same number of as specified in our first contention. va_arg is the large scale used to peruse a contention from the list. It takes two parameters: the va_list question we made, args, and an information sort. va_arg will give back the following contention as this sort.

At long last, we give back the aggregate we figured in the function.

Conclusion

You ought to now know how to make a C function that acknowledges a variable number of arguments at runtime. This system is especially helpful while making wrapper functions for functions that as of now acknowledge a variable number of arguments, for example, printf(). This is exhibited in my other instructional exercise, Writing a Custom printf() Wrapper Function in C.

void sample(int i, va_list args) {
/* Do NOT call va_start or va_end */
}
void example(int i, int j, ...)
{
va_list args;
va_start(args, b);
sample(b, args);
va_end(args);
}

I generally welcome inquiries or input about this instructional exercise. Essentially post an answer or PM me; I’m happy to offer assistance!

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version