2

I would like to make a function that can take a variable number of parameters at once to do something like this:

void function(char *args[]){ ... } 

int main(){
   function("a","b","c");
}
1
  • The example you've shown can't work, because there's no way for function to know that there are three arguments this time. Commented Feb 2, 2022 at 16:34

1 Answer 1

7

You are looking for Variadic functions.

Check this example:

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

double average(int num, ...) {

   va_list valist;
   double sum = 0.0;
   int i;

   /* initialize valist for num number of arguments */
   va_start(valist, num);

   /* access all the arguments assigned to valist */
   for (i = 0; i < num; i++) {
      sum += va_arg(valist, int);
   }
    
   /* clean memory reserved for valist */
   va_end(valist);

   return sum/num;
}

int main(void) {
   printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2, 3, 4, 5));
   printf("Average of 5, 10, 15 = %f\n", average(3, 5, 10, 15));
}

Output:

Average of 2, 3, 4, 5 = 3.500000
Average of 5, 10, 15 = 10.000000

Read more in Variadic Functions in C and the Reference.


Tip: Think twice before using Variadic functions. As @user694733 commented, they have no compile time type safety or protection against invalid number of arguments. They can usually be avoided with better program design.

Sign up to request clarification or add additional context in comments.

4 Comments

This answer is correct, but I would like to give standard warning: Do not use variadic functions unless absolutely necessary! They have no compile time type safety or protection against invalid number of arguments. They can usually be avoided with better program design.
@user694733 good advice, thank you! I've updated my answer including a reference too. ;)
@user694733 Me, I'd say your comment is the logical equivalent of Do not use a chainsaw unless absolutely necessary! I mean, yes, chainsaws are dangerous, and yet, they exist.
@SteveSummit More like: regular functions are standard chainsaws, and variadic function is chainsaw with slightly sharper teeth, but it's always on and emergency brake has been removed. In my experience, variadic functions seem like good idea at first, but end up being replaced with little less convenient but safer alternatives sooner or later. Only exception is perhaps printf-like logging functions, but even those are often used with special compiler pragmas to enable extra argument validation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.