C语言变参函数/Variadic fucntion

几个重要的 宏/类型 定义

Macros Defined in header <stdarg.h>
va_start enables access to variadic function arguments (function macro)
va_arg accesses the next variadic function argument (function macro)
va_copy (C99) makes a copy of the variadic function arguments (function macro)
va_end ends traversal of the variadic function arguments (function macro)
Type
va_list holds the information needed by va_start, va_arg, va_end, and va_copy (typedef)

在C语言的库文件 stdarg.h中包含带参数的宏定义

typedef void *va_list;
#define va_arg(ap,type) (*((type *)(ap))++) //获取指针ap指向的值,然后ap=ap+1,即ap指向下一个值,其中<u>type</u>是 变参数的类型,可以是char(cter), int(eger), float等。
#define va_start(ap,lastfix) (ap=…)
#define va_end(ap) // 清理/cleanup 指针ap

例子

#include <stdio.h>
#include <stdarg.h>
 
void simple_printf(const char* fmt, ...)
{
    va_list args;
    va_start(args, fmt);
 
    while (*fmt != '') {
        if (*fmt == 'd') {
            int i = va_arg(args, int);
            printf("%d
", i);
        } else if (*fmt == 'c') {
            // note automatic conversion to integral type
            int c = va_arg(args, int);
            printf("%c
", c);
        } else if (*fmt == 'f') {
            double d = va_arg(args, double);
            printf("%f
", d);
        }
        ++fmt;
    }
 
    va_end(args);
}
 
int main(void)
{
    simple_printf("dcff", 3, 'a', 1.999, 42.5); 
}

参考:
Variadic functions
C语言变参函数解析
C语言的变参函数设计

原文地址:https://www.cnblogs.com/xuanyuanchen/p/6006423.html