Menu
Coddy logo textTech

Variadic Function

Lesson 10 of 17 in Coddy's Functions in C course.

In C, as in other programming languages, there is a concept called a variadic function, which is a function that accepts an unlimited number of parameters.

To use a variadic function, we first need to include the <stdarg.h> header file.

Let's look at an example to see how this works:

#include <stdio.h>
#include <stdarg.h>
int sum(int num, ...) {
   va_list list;        
   va_start(list, num);
   int sum = 0;
   for (int i = 0; i < num; i++) {
       sum += va_arg(list, int); 
   }
   va_end(list); 
   printf("%d", sum);
}
int main() {
    sum(2, 20, 30);          
   return 0;
}

In this example, the sum function calculates the sum of a variable number of integer values.

  1. Declare a variable to hold the argument list using the <strong>va_list</strong> macro:

    va_list list;
  2. Initialize the argument list:

    va_start(list, num);
  3. Declare a variable to hold the sum:

    int sum = 0;
  4. Loop through all the elements, retrieve each argument, and add it to the sum:

    for (int i = 0; i < num; i++) {
           sum += va_arg(list, int); 
       }
  5. Clean up the argument list after the calculations are done:

     va_end(list); 
  6. In the <strong>main</strong> function, call the <strong>sum</strong> function like this:

      sum(2, 20, 30);  

     

 

challenge icon

Challenge

Easy

Using a variadic function, create a function called average that calculates and print the average of student grades.

Try it yourself

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

// Function to calculate the average 


int main() {
    
    // Call the variadic function | Don't Change this
    average(4, 85, 90, 78, 92);

    return 0;
}

All lessons in Functions in C