如何通过,如果参数的数目不详的va_list循环? [英] How to loop through a va_list if the number of arguments is unknown?

查看:585
本文介绍了如何通过,如果参数的数目不详的va_list循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何通过循环的va_list如果额外的参数数是未知的?

 的#include<&stdio.h中GT;
#包括LT&;&STDARG.H GT;加INT(INT X,INT Y){
    va_list的intargs;
    INT温度= 0;    的va_start(intargs,Y);
    INT I;
    对于(i = 0;我3;;我++){/ *我怎么能遍历任意数量args来? * /
        温度+ =在va_arg(intargs,INT);
    }
    va_end用来(intargs);    回温+ X + Y;
}诠释主(){
    的printf(总为%d \\ n,加(1,2,3,4,5));
    返回0;
}


解决方案

使用的警戒值作为终止,如 NULL 1

How do I loop through a va_list if the number of additional arguments is unknown?

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

int add(int x, int y, ...) {
    va_list intargs;
    int temp = 0;

    va_start(intargs, y);
    int i;
    for (i = 0; i < 3; i++) { /* How can I loop through any number of args? */ 
        temp += va_arg(intargs, int);
    }
    va_end(intargs);

    return temp + x + y;
}

int main() {
    printf("The total is %d.\n", add(1, 2, 3, 4, 5));
    return 0;
}

解决方案

Use a sentinel value as a terminator, e.g NULL or -1

这篇关于如何通过,如果参数的数目不详的va_list循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆