可以接收数量不定的参数的函数

#include <iostream>
#include <cstdarg>

int sum(int count, ...)
{//接收数量不定的参数
    if (count <= 0)
        return 0;
    va_list argList;
    va_start(argList, count);
    int sum = 0;
    for (int i = 0; i < count; ++i)
    {
        sum += va_arg(argList, int);
    }
    va_end(argList);
    return sum;
}

int main(int argc, char* argv[])
{
    int ret;
    ret = sum(3, 1, 2, 3);//6
    ret = sum(4, 0, 9, 8, 5);//22

    system("pause");
    return 0;
}

 

posted @ 2019-08-31 10:49  htj10  阅读(176)  评论(0编辑  收藏  举报
TOP