在C使用可变参数的例子 [英] An example of use of varargs in C

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

问题描述

这里我发现如何可变参数的例子C中使用。

 的#include<&STDARG.H GT;双平均值(诠释计数,...)
{
    va_list的AP;
    诠释J;
    双TOT = 0;
    的va_start(AP,计数); //需要的最后一个固定参数(获取地址)
    为(J = 0; J<计数; J ++)
        TOT + =在va_arg(AP,双面); //需要投的类型。 AP递增到下一个参数。
    va_end用来(AP);
    返回TOT /计数;
}

我能理解这个例子只是在一定程度上。


  1. 这是我不明白为什么我们使用的va_start(AP,计数); 。据我了解,这样我们设定的迭代器的第一个元素。但是,为什么它没有被设置为一开始默认?


  2. 这是我不清楚为什么我们需要给计数作为参数。能不能用C ++自动确定的参数的数目?


  3. 为什么我们使用 va_end用来(AP)是我不清楚。是什么改变?是否设置迭代器列表的末尾?但它没有设置为名单中循环的结束?此外,我们为什么需要它。我们不使用 AP 了,我们为什么要改变它?



解决方案

记住,参数在栈上传递。在的va_start 功能包含了神奇code用正确的堆栈指针初始化的va_list 。它的必须的传递函数声明的最后一个命名参数,否则将无法正常工作。

什么的va_arg 确实是使用这个存储堆栈指针,并提取所提供的类型正确的字节数量,然后修改 AP 使其指向堆栈中的下一个参数。


在现实中这些功能(的va_start 的va_arg va_end用来)实际上不是功能,而是作为preprocessor宏来实现。实际执行也取决于编译器,如不同的编译器可以具有叠层的不同的布局,以及它如何在栈上推自变量。

Here I found an example of how varargs can be used in C.

#include <stdarg.h>

double average(int count, ...)
{
    va_list ap;
    int j;
    double tot = 0;
    va_start(ap, count); //Requires the last fixed parameter (to get the address)
    for(j=0; j<count; j++)
        tot+=va_arg(ap, double); //Requires the type to cast to. Increments ap to the next argument.
    va_end(ap);
    return tot/count;
}

I can understand this example only to some extent.

  1. It is not clear to me why we use va_start(ap, count);. As far as I understand, in this way we set the iterator to its first element. But why it is not set to the beginning by default?

  2. It is not clear to me why we need to give count as an argument. Can't C++ automatically determine the number of the arguments?

  3. It is not clear to me why do we use va_end(ap). What does it change? Does it set iterator to the end of the list? But is it not set to the end of the list by the loop? Moreover, why do we need it. We do not use ap anymore, why do we want to change it?

解决方案

Remember that arguments are passed on the stack. The va_start function contains the "magic" code to initialize the va_list with the correct stack pointer. It must be passed the last named argument in the function declaration or it will not work.

What va_arg does is use this saved stack pointer, and extract the correct amount of bytes for the type provided, and then modify ap so it points to the next argument on the stack.


In reality these functions (va_start, va_arg and va_end) are not actually functions, but implemented as preprocessor macros. The actual implementation also depends on the compiler, as different compilers can have different layout of the stack and how it pushes arguments on the stack.

这篇关于在C使用可变参数的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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