相关疑难解决方法(0)

C++中函数的可变参数数量

如何在C++中的函数中包含可变数量的参数.

C#中的模拟:

public void Foo(params int[] a) {
    for (int i = 0; i < a.Length; i++)
        Console.WriteLine(a[i]);
}

public void UseFoo() {
    Foo();
    Foo(1);
    Foo(1, 2);
}
Run Code Online (Sandbox Code Playgroud)

Java中的模拟:

public void Foo(int... a) {
    for (int i = 0; i < a.length; i++)
        System.out.println(a[i]);
}

public void UseFoo() {
    Foo();
    Foo(1);
    Foo(2);
}
Run Code Online (Sandbox Code Playgroud)

c c++ syntax variadic-functions

31
推荐指数
4
解决办法
7万
查看次数

将参数动态传递给可变参数函数

我想知道是否有任何方法可以动态地将参数传递给可变参数函数.即如果我有一个功能

int some_function (int a, int b, ...){/*blah*/}
Run Code Online (Sandbox Code Playgroud)

我接受用户的一堆值,我想要一些方法将这些值传递给函数:

some_function (a,b, val1,val2,...,valn)
Run Code Online (Sandbox Code Playgroud)

我不想写所有这些功能的不同版本,但我怀疑没有其他选择?

c dynamic variadic argument-passing

5
推荐指数
2
解决办法
5673
查看次数

C函数中的变量参数列表 - 如何正确遍历arg列表?

在以下C程序中,我收到警告:

warning #2030: '=' used in a conditional expression.

究竟是什么问题,我该如何避免这个?迭代变量参数的正确方法是什么?

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

int Sum(int a, int b, ...)
{
    int arg;
    int Sum = a + b;

    va_list ap;
    va_start(ap, b);

    while(arg = va_arg(ap, int))
    {
        Sum += arg;
    }
    va_end(ap);

    return Sum;
}

int main(int argc, char *argv[])
{
    printf("%d\n", Sum(1, 2, 4, 8));

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c variables arguments function

5
推荐指数
1
解决办法
7248
查看次数

Help me understand this short chunk of code

I understand this code calculates the sum of the args of a variable, however, I don't understand how it works. It looks really abstract to me. Can someone explain how the below works?

Thanks!

#include <stdio.h>

#define sum(...) \
    _sum(sizeof((int []){ __VA_ARGS__ }) / sizeof(int), (int []){ __VA_ARGS__ })

int _sum(size_t count, int values[])
{
    int s = 0;
    while(count--) s += values[count];
    return s;
}

int main(void)
{
    printf("%i", sum(1, 2, 3));
}
Run Code Online (Sandbox Code Playgroud)

c

4
推荐指数
1
解决办法
739
查看次数