Variadic Functions in C

 Variadic Functions in C


Variadic functions allow you to define functions that can accept a variable number of arguments. This is useful when you want to create functions with a flexible number of parameters.


#include <stdio.h>

#include <stdarg.h>


double average(int count, ...) {

    double sum = 0;


    va_list args;

    va_start(args, count);


    for (int i = 0; i < count; i++) {

        sum += va_arg(args, int);

    }


    va_end(args);


    return sum / count;

}


int main() {

    double avg1 = average(3, 2, 4, 6);

    double avg2 = average(5, 1, 3, 5, 7, 9);


    printf("Average 1: %.2f\n", avg1);

    printf("Average 2: %.2f\n", avg2);


    return 0;

}

In this example, the average function takes a variable number of integer arguments and calculates their average. The stdarg.h header provides the necessary functions and macros to work with variadic arguments.


No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...