C语言不定参数的两种实现

1、使用以下三个函数可实现不定参数

#include<stdarg.h>

void va_start(va_list ap, last);
type va_arg(va_list, type);
void va_end(va_list ap);

《1》、va_start
该函数用来初始化指针变量ap(va_list实际是void类型),之后处理参数就默认从ap开始处理。last一般为传过来的参数列表的第一个参数。
《2》、va_arg
该函数就是将ap指针按照type类型向后移动,然后返回ap所指的那个参数。
注意:
type类型不能是float,其它不支持暂不知(测试过char
,int, short均可以)
《3》、va_end
和va_start配套使用,做善后。

#include<stdarg.h>
#include <stdio.h>

//count 人为将参数个数传递进去
int test(int count, short first, ...)
{
    va_list argp;
    int sum = 0;
    int tmp = 0;
    va_start(argp, first);
    printf("%d \t", first);
    for (int i = 1; i < count; ++i)
    {
        printf("%d \t", va_arg(argp,short));
    }
    
    va_end(argp);
    return 0;
}

int main()
{
    test(10, 5, 6, 8, 9, 10, 56, 89, 52, 21, 110);
    getchar();
    return 0;
}

2、可变参数宏 …和__VA_ARGS__
C99规范中新增的宏

#define debug(format, ...)    fprintf(stdout, format, __VA_ARGS__)
int test(int count, short first, ...)
{
    va_list argp;
    int sum = 0;
    int tmp = 0;
    va_start(argp, first);
    printf("%d \t", first);
    for (int i = 1; i < count; ++i)
    {
        debug("%d \t", va_arg(argp,short));
     //printf("%d \t", va_arg(argp,short));
    }
    
    va_end(argp);
    return 0;
}

3、参考
《1》、https://www.cnblogs.com/linhaostudy/p/6695422.html;
《2》、https://www.cnblogs.com/alexshi/archive/2012/03/09/2388453.html
8、

猜你喜欢

转载自blog.csdn.net/FPGATOM/article/details/84716827