C PROGRAMMING

Variadic Functions

Date Published:
Last Modified:

Overview

Variadic functions are functions which can take in a variable number of arguments. The C language by itself provides no special syntax for dealing with them, but variadic functions are supported by the standard C library (<varargs.h>).

Syntax

A variadic function is declared as:

MyFunction(uint32_t arg1, ...);

Where MyFunction is defined as a function which takes 1 required argument, and as many non-optional arguments as you want (up to the practical limit set by the maximum number of function arguments you are allowed).

A variadic function is defined as:

MyFunction(arg1, ...)
{
    // function code goes here
}

But how do you access the variable arguments in your function definition? Use the function-like macros va_start, va_arg and va_end provided by <varargs.h>.

MyFunction(uint32_t arg1, ...)
{
    // Create a variable of va_list type to access the variable arguments
    va_list varArgs;

    
    va_start(varArgs);
    for (uint32_t j = 0; j < arg1; j++)
    {
        sum += va_arg(varArgs);
    }

    // Make sure always call va_end after you are finished with the variable arguments. For most compilers, this is an empty function (including GCC).
    va_end(ap);
}

The second argument passed to va_arg, type, must be a self-promoting type.

For most compilers, va_end does nothing (including the GCC compiler). But you should always include it for portability reasons.


Tags:

    comments powered by Disqus