Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

77
Views
C - Function with Variadic Arguments

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");
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!