The Wayback Machine - https://web.archive.org/web/20250114123546/https://www.geeksforgeeks.org/variadic-functions-in-c/
Open In App

Variadic Functions in C

Last Updated : 17 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C, variadic functions are functions that can take a variable number of arguments. This feature is useful when the number of arguments for a function is unknown. It takes one fixed argument and then any number of arguments can be passed.

Let’s take a look at an example:

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

// Variadic function to print given arguments
void print(int n, ...) {
    va_list args;
    va_start(args, n);  
    for (int i = 0; i < n; i++) 
        printf("%d ", va_arg(args, int));
    printf("\n");
    va_end(args);
}


int main() {
  
      // Calling function sum() with different number
      // of arguments
    print(3, 1, 2, 3);
    print(5, 1, 2, 3, 4, 5);
  
    return 0;
}

Output
1 2 3 
1 2 3 4 5 

Explanation: In this example, the sum() function takes a fixed first parameter n and the rest parameters vary. We have called this function with 3 and 5 arguments and it was able to work for both.

Syntax of Variadic Functions

A variadic function takes at least one fixed argument an ellipsis(â€Ķ) as the last parameter.

return_type name(fixed_arg, …);

Accessing Variable Arguments

The above syntax allows users to pass the variable arguments, but to access the variable arguments inside the function, we have to use the methods specified in the <stdarg.h> library. The step-by-step process for this is as follows:

1. Create the Variable Argument List – valets

Use the va_list type to declare a variable that will store the information needed to retrieve the additional arguments.

va_list list;

2. Initialize the Argument List – va_start()

This macro initializes the va_list to retrieve arguments from the variable arguments section.

va_start(list, fixed_arg);

where,

  • list: The va_list to initialize.
  • fixed_arg: The last fixed argument before the variable arguments (…).

3. Retrieve Arguments – va_arg

This macro returns the next argument from the list. It must be used repeatedly to access all arguments.

va_arg(list, type);

The number of times it should be called should not exceed the number of parameters passed. Due to this, the count of variable arguments passed is also passed as fixed parameters.

where,

  • type: The type of the argument to retrieve.

Note: It is important to not mix up the type of the arguments.

4. Clean Up with va_end()

Once all the arguments are processed, use va_end() to clean up the va_list. This ensures that resources associated with va_list are properly released.

va_end(list);

Examples of Variadic Functions

The below examples demonstrate the use of variadic functions in C language:

Find the Sum of Given Numbers

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

// Variadic function to add numbers
int getSum(int n, ...) {
    int sum = 0;

    // Declaring a va_list pointer to
    // argument list
    va_list list;

    // Initializing argument to the
    // list pointer
    va_start(list, n);

    for (int i = 0; i < n; i++)

        // Accessing current variable
        // and pointing to next one
        sum += va_arg(list, int);

    // Ending argument list traversal
    va_end(list);

    return sum;
}
int main() {
    // Variable number of arguments
    printf("1 + 2 = %d\n",
           getSum(2, 1, 2));

    printf("3 + 4 + 5 = %d\n",
           getSum(3, 3, 4, 5));

    printf("6 + 7 + 8 + 9 = %d",
           getSum(4, 6, 7, 8, 9));

    return 0;
}

Output
1 + 2 = 3
3 + 4 + 5 = 12
6 + 7 + 8 + 9 = 30

Explanation: The getSum() function calculates the sum of n variable arguments by iterating through the list of arguments and adding each one to a sum. It uses va_list, va_start, and va_arg to handle the variable arguments and returns the sum.

Variadic Function with Mixed Arguments

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

// Variadic function that prints different types of arguments
void print(int n, ...) {
    va_list args;
  
    // Initialize args
    va_start(args, n);  

    for (int i = 0; i < n; i++) {
        if (i % 2 == 0) {
            printf("Integer: %d\n", va_arg(args, int));
        } else {
            printf("Float: %.2f\n", va_arg(args, double));
        }
    }

    // Clean up
    va_end(args);  
}

int main() {
    print(4, 10, 3.14, 20, 2.71);
    return 0;
}

Output
Integer: 10
Float: 3.14
Integer: 20
Float: 2.71

Explanation: In this example, print() takes an integer count as the first parameter, followed by a variable number of arguments. We use va_arg to print integers and floats alternately, based on their position in the argument list.

Variadic Functions in C – FAQs

Can variadic functions accept arguments of different data types?

Yes, but the function must explicitly manage the data types using va_arg() and know the expected type for each argument.

Is it necessary to have a fixed parameter in a variadic function?

While it’s not strictly necessary, a fixed parameter is typically used to specify the number or type of the variable arguments to make processing safer and easier.

What happens if the number of arguments passed doesn’t match the expected count in a variadic function?

This can lead to undefined behavior. It is important to use mechanisms like a fixed parameter or sentinel values to ensure that the function processes the correct number of arguments.

Can we only have one fixed parameter in a variadic function?

No, we can have multiple fixed parameters in variadic function, but the last parameter should be ellipses.


Master C programming with our C Programming Course Online, which covers everything from the basics to advanced concepts like data structures. Gain a deep understanding of C and enhance your problem-solving abilities with practical coding challenges.

Take the Three 90 Challenge! Complete 90% of the course in 90 days, and earn a 90% refund. Track your learning journey and get rewarded for your commitment.
Join now and start mastering C programming!


Next Article

Similar Reads

three90RightbarBannerImg