Variadic Functions

Article by:
Date Published:
Last Modified:


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>).


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;

    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).

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.


Geoffrey Hunter

Dude making stuff.

Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License .


comments powered by Disqus
Page contents: