|
Variadic Functions in C
An Introduction |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
void formal parameter:
int max(int a, int b, ...)
max(10, 5, 13, 7, 9, -1)
char array) to
provide information about the number of other parametersprintf("%d %d %d %d %d", 10, 5, 13, 7, 9)
<stdarg.h>
va_list: Data typevoid va_start(va_list ap, type last_fixed): Initialize the argument pointertype va_arg(va_list ap, type): Return the next argument (and update ap)void va_end(va_list ap): Clean upvoid va_copy(va_list destination, va_list source)
#include <stdarg.h>
#include "extremes.h"
// Find the maximum of 2 (or more) non-negative integers.
// (Note: Pass a negative value as the last parameter.)
int
max(int a, int b, ...)
{
int current, result;
va_list last_fixed;
// Handle the two required parameters
result = -1;
if (a > result) result = a;
if (b > result) result = b;
// Handle the variable number of parameters
va_start(last_fixed, b);
do
{
current = va_arg(last_fixed, int);
if (current > result) result = current;
} while (current >= 0); // The sentinel hasn't been encountered
va_end(last_fixed);
return result;
}
typedef char *va_list; #define va_start(ap, v) (ap=(va_list) _ADDRESSOF(v) + _INTSIZEOF(v)) #define va_arg(ap, t) (*(t *)((ap += _INTSIZEOF(t)) - INTSIZEOF(t))) #define va_end(ap) (ap = (va_list)0)
va_start() then allocates memory and
va_end() later frees memory