Variadic functions in C

  • + 1 comment

    This is a simple problem - if you've worked with variadic functions before! Otherwise you won't have a clue how to get started, based on that problem description. This is where it's handy to have done embedded programming - we avoid standard libraries and any bloat they might have, so I've had to roll my own version of printf.

    This is C's way of handling an unknown number of arguments that can be passed in to a function.

    In the function you need declare a variable of type va_list, let's call it val. Think of it as a linked list and the items are of any type. You tell it where to set the initial pointer using the argument passed in before the ellipse ... in this case count. So that looks like: va_start (val, count);
    Next you get items from that list using va_arg, you need to tell it what type of item is on the list. We're dealing with ints, so this is tempval = va_arg(val, int). This just traverses the list, make sure you don't go off the end. It auto-increments to the next item. Finally, clean it up with va_end (val);