C PROGRAMMING

Variadic Functions

Article by:
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:

1
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:

1
2
3
4
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>.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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.


Authors

Geoffrey Hunter

Dude making stuff.

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

Tags

    comments powered by Disqus