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 <stdio.h>
#include <stdarg.h>

int sum(unsigned int count, const int , ...);

int main(void)
{
    printf("The result is:%d\n", sum(3, 10, 9, 8));
    return 0;
}
int sum(unsigned int count, const int first, ...)
{
    va_list argp;
    int i;
    int sum = 0;
    int tmp;
    va_start(argp, first);
    sum += first;
    printf("%d\n", first);
    for ( i = 1; i < count; i++)
    {   
        /* code */
        tmp = va_arg(argp, int);
        printf("%d\n", tmp);
        sum += tmp;
    }
    
    va_end(argp);
    return sum;
}

结果:

10
9
8
The result is:27

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

通过宏的方式可以在
语言中自定义打印的输出函数,不在打印的函数中增加例如行、函数名或者所在的文件名等,该例子采用自定义打印不定参数函数的例子来举例。

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

#define debug(format, ...) do{\
    printf("Info %s,%s,%d, "format"\n",__FILE__,__FUNCTION__,__LINE__,__VA_ARGS__);\
}while(0)

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, int));
     //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;
}

其中自定的打印参数为:

#define debug(format, ...) do{\
    printf("Info %s,%s,%d, "format"\n",__FILE__,__FUNCTION__,__LINE__,__VA_ARGS__);\
}while(0)

详解:

debug的第一个参数format为待打印信息的格式,和print函数中的%d、%s等类似。
在print中需要在打印字符串中将格式化的参数用双引号表示这个是输入的格式参数。不是需要打印的字符串。

我们可以使用一个简单的自定义的打印函数来测试一下format参数的含义

#define debug(format, ...)    fprintf(stdout, format, __VA_ARGS__)

以上程序运行的结果为:

5       Info a.c,test,44, 6 
Info a.c,test,44, 8 
Info a.c,test,44, 9 
Info a.c,test,44, 10 
Info a.c,test,44, 56 
Info a.c,test,44, 89 
Info a.c,test,44, 52 
Info a.c,test,44, 21 
Info a.c,test,44, 110 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

绛洞花主敏明

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值