变量列表参数 [英] Variadic list parameter

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

问题描述

说我有两个函数

void f1(int p1, int v1, ...);

AND

void f2(int v1, ...);

里面f1我想将所有参数从可变参数列表传递到f2:

Inside f1 I want to pass all parameters from variadic list to f2:

void f1(int p1, int v1, ...) {
   f2(/*pass all variadic parameters*/);
}

例如,当我调用 f1 ,3,4,5)我想传递2,3,4,5到 f2

For example when I call f1(1, 2, 3, 4, 5) I want to pass 2,3,4,5 to f2

推荐答案

这不可能直接,但你可以使用 va_list 类型来包装完整的值并传递到采用这样的参数的函数的版本。基本上,将 f2()转换成:

It's not possible directly, but you can use the va_list type to wrap the full complement of values and pass them to a version of the function that takes such an argument. Basically, break f2() into:

void f2v(int v1, va_list args) {
    // ...
    // use va_arg() repeatedly to get the various arguments here
}

void f2(int v1, ...) {
    va_list args;
    va_start(args, v1);
    f2v(v1, args);
    va_end(args);
}

然后重做 f1 $ c>使用 f2v()而不是 f2()

void f1(int p1, int v1, ...) {
    // do whatever else you need to do before the call to f2

    va_list args;
    va_start(args, v1);
    f2v(v1, args);
    va_end(args);

    // do whatever else you need to do after the call to f2
}

这理论上是 printf() vprintf() code> printf()在内部可以调用 vprintf(),因此不需要两个功能相同的实现。

This is, in theory, how printf() and vprintf() work--printf() internally can call vprintf() so that two functionally identical implementations are not needed.

(不要忘记 - 您需要 #include< stdarg.h> 才能访问 va_list va_start()等)

(Don't forget--you need to #include <stdarg.h> to get access to va_list, va_start(), etc.)

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

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