passing variable number of arguments

跟風遠走 提交于 2019-11-26 23:36:33

问题


Can we pass variable number of arguments to a function in c?


回答1:


Here is an example:

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

int maxof(int, ...) ;
void f(void);

int main(void){
        f();
        exit(EXIT SUCCESS);
}

int maxof(int n_args, ...){
        register int i;
        int max, a;
        va_list ap;

        va_start(ap, n_args);
        max = va_arg(ap, int);
        for(i = 2; i <= n_args; i++) {
                if((a = va_arg(ap, int)) > max)
                        max = a;
        }

        va_end(ap);
        return max;
}

void f(void) {
        int i = 5;
        int j[256];
        j[42] = 24;
        printf("%d\n", maxof(3, i, j[42], 0));
}



回答2:


If it is a function that accepts a variable number of arguments, yes.




回答3:


Yes, if the function accepts variable arguments. If you need to make your own variable-argument function, there are macros that begin with va_ which give you access to the arguments.




回答4:


make sure that the variable argument list should always be at the end of the argument list

example: void func(float a, int b, ...) is correct

but void func(float a, ..., int b) is not valid




回答5:


"You should consider that using variadic functions (C-style) is a dangerous flaw," says Stephane Rolland. You can find his helpful post here.



来源:https://stackoverflow.com/questions/3836272/passing-variable-number-of-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!