本文介绍了在C变量元数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道我如何能够实现C语言为函数的变量参数数量?

Does anyone knows how I might be able to implement variable arity for functions in C?

例如,一个加法功能:

总和(1,2,3,4 ...); (args中的变量数注意到)

Sum(1,2,3,4...); (Takes in a variable number of args)

谢谢!

推荐答案

int型变量参数列表。根据需要调整类型:

A variable parameter list of ints. Adjust type as necessary:

#include <stdarg.h>

void myfunc(int firstarg, ...)
{
    va_list v;
    int i = firstarg;

    va_start(v, firstarg);
    while(i != -1)
    {
        // do things
        i = va_arg(v, int);
    }

    va_end(v);
}

您必须能够确定何时停止读取变量ARGS。这是一个终结的说法做(-1在我的例子),或从其他来源知道args来预计数(例如,通过检查格式化字符串作为printf的)。

You must be able to determine when to stop reading the variable args. This is done with a terminator argument (-1 in my example), or by knowing the expected number of args from some other source (for example, by examining a formatting string as in printf).

这篇关于在C变量元数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 04:38