Linux C 函数是否支持任意数量的参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3677136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:18:04  来源:igfitidea点击:

Do C functions support an arbitrary number of arguments?

c

提问by alex

PHP has a func_get_args()for getting all function arguments, and JavaScript has the functionsobject.

PHP 有一个func_get_args()用于获取所有函数参数,而 JavaScript 有这个functions对象。

I've written a very simple max()in C

我用max()C写了一个非常简单的

int max(int a, int b) {

    if (a > b) {
        return a;   
    } else {
        return b;
    }
}

I'm pretty sure in most languages you can supply any number of arguments to their max()(or equivalent) built in. Can you do this in C?

我很确定在大多数语言中,您可以为其max()内置的(或等效的)提供任意数量的参数。您可以在 C 中执行此操作吗?

I thought this questionmay have been what I wanted, but I don't think it is.

我认为这个问题可能是我想要的,但我认为不是。

Please keep in mind I'm still learning too. :)

请记住,我也在学习。:)

Many thanks.

非常感谢。

采纳答案by AndiDog

You could write a variable-arguments function that takes the number of arguments, for example

例如,您可以编写一个接受参数数量的可变参数函数

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

int sum(int numArgs, ...)
{
    va_list args;
    va_start(args, numArgs);

    int ret = 0;

    for(unsigned int i = 0; i < numArgs; ++i)
    {
        ret += va_arg(args, int);
    }    

    va_end(args);

    return ret;
}    

int main()
{
    printf("%d\n", sum(4,  1,3,3,7)); /* prints 14 */
}

The function assumes that each variable argument is an integer (see va_argcall).

该函数假定每个变量参数都是一个整数(参见va_arg调用)。

回答by paxdiablo

Yes, C has the concept of variadic functions, which is similar to the way printf()allows a variable number of arguments.

是的,C 有可变参数函数的概念,它类似于printf()允许可变数量参数的方式。

A maximum function would look something like this:

最大函数看起来像这样:

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

static int myMax (int quant, ...) {
    va_list vlst;
    int i;
    int num;
    int max = INT_MIN;

    va_start (vlst, quant);

    for (i = 0; i < quant; i++) {
        if (i == 0) {
            max = va_arg (vlst, int);
        } else {
            num = va_arg (vlst, int);
            if (num > max) {
                max = num;
            }
        }
    }
    va_end (vlst);
    return max;
}

int main (void) {
    printf ("Maximum is %d\n", myMax (5, 97, 5, 22, 5, 6));
    printf ("Maximum is %d\n", myMax (0));
    return 0;
}

This outputs:

这输出:

Maximum is 97
Maximum is -2147483648

Note the use of the quantvariable. There are generally two ways to indicate the end of your arguments, either a count up front (the 5) or a sentinel value at the back.

注意quant变量的使用。通常有两种方法可以指示参数的结尾,一个是前面的计数(the 5),另一个是后面的标记值。

An example of the latter would be a list of pointers, passing NULLas the last. Since this maxfunction needs to be able to handle the entire range of integers, a sentinel solution is not viable.

后者的一个例子是一个指针列表,NULL作为最后一个传递。由于此max函数需要能够处理整个整数范围,因此哨兵解决方案不可行。

The printffunction uses the former approach but slightly differently. It doesn't have a specific count, rather it uses the %fields in the format string to figure out the other arguments.

printf函数使用前一种方法,但略有不同。它没有特定的count,而是使用%格式字符串中的字段来计算其他参数。

回答by Tristan

here is a link to site that shows an example of using varargs in c Writing a ``varargs'' Function

这是一个站点链接,该链接显示了在 c 中使用可变参数的示例编写“可变参数”函数

You can use the va_args function to retrieve the optional arguments you pass to a function. And using this you can pass 0-n optional parameters. So you can support more then 2 arguments if you choose

您可以使用 va_args 函数来检索传递给函数的可选参数。使用它您可以传递 0-n 个可选参数。因此,如果您选择,您可以支持超过 2 个参数

回答by torak

Yes, you can declare a variadicfunction in C. The most commonly used one is probably printf, which has a declaration that looks like the following

是的,您可以在 C 中声明一个可变参数函数。最常用的可能是printf,它的声明如下所示

int printf(const char *format, ...);

The ...is how it declares that it accepts a variable number of arguments.

...就是它声明它接受可变数量参数的方式。

To access those argument it can uses va_start, va_argand the like which are typically macros defined in stdarg.h. See here

要访问这些参数,它可以使用va_startva_arg等等,它们通常是stdarg.h. 看这里

It is probably also worth noting that you can often "confuse" such a function. For example the following call to printfwill print whatever happens to be on the top of the stack when it is called. In reality this is probably the saved stack base pointer.

可能还值得注意的是,您经常会“混淆”这样的函数。例如,以下调用printf将打印调用时堆栈顶部发生的任何内容。实际上,这可能是保存的堆栈基指针。

printf("%d");

回答by Jens Gustedt

In fact, this are two questions. First of all C99 only requires that a C implementation may handle at least:

其实这是两个问题。首先,C99 只要求 C 实现至少可以处理:

  • 127 parameters in one function definition
  • 127 arguments in one function call
  • 一个函数定义中包含 127 个参数
  • 一个函数调用中有 127 个参数

Now, to your real question, yes there are so-called variadic functions and macros in C99. The syntax for the declaration is with ...in the argument list. The implementation of variadic functions goes with macros from the stdarg.hheader file.

现在,对于您真正的问题,是的,C99 中有所谓的可变参数函数和宏。声明的语法...在参数列表中。可变参数函数的实现与stdarg.h头文件中的宏一起使用。

回答by pmg

Ccan have functions receive an arbitrary number of parameters.

C可以让函数接收任意数量的参数。

You already know one: printf()

你已经知道一个: printf()

printf("Hello World\n");
printf("%s\n", "Hello World");
printf("%d + %d is %d\n", 2, 2, 2+2);

There is no maxfunction which accepts an arbitrary number of parameters, but it's a good exercise for you to write your own.

没有任何max函数可以接受任意数量的参数,但是您可以自己编写一个很好的练习。

Use <stdarg.h>and the va_list, va_start, va_arg, and va_endidentifiers defined in that header.

使用<stdarg.h>va_listva_startva_arg,并va_end在头文件中定义的标识符。

http://www.kernel.org/doc/man-pages/online/pages/man3/stdarg.3.html

http://www.kernel.org/doc/man-pages/online/pages/man3/stdarg.3.html

回答by tenfour

Another alternative is to pass in an array, like main(). for example:

另一种选择是传入一个数组,例如main(). 例如:

int myfunc(type* argarray, int argcount);

int myfunc(type* argarray, int argcount);