9

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

3
  • 3
    Such a function is called a variadic function (for those seeking good search keywords).
    – Seth
    Oct 1, 2010 at 3:11
  • Haven't you ever used printf?
    – dan04
    Oct 1, 2010 at 6:00
  • I have used it but didnt know much about using variadic functions.
    – Shweta
    Oct 1, 2010 at 8:25

5 Answers 5

11

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
  • 1
    I don't get the use of the register here? Dec 9, 2011 at 21:25
  • The use of register is evidence that the code sample is quite old. Use of register is a hint to the compiler to place the variable into a machine register, as a performance optimisation. The majority of C compilers over the last 30 years have ignored that hint, since they can do a better job of register allocation than most programmers can. Nowadays, register has few effects other than forbidding calculation of the address of a variable.
    – Peter
    Jul 21, 2017 at 13:44
6

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

0

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.

0
0

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

1
  • Yes, but this is more of a comment than an answer. Certainly, you've explained one aspect, but it is a very minor aspect of the answer. Jul 21, 2017 at 13:33
0

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

1
  • 1
    I believe the advice is for writing your own custom variadic functions in C++ and not for the ones provided by the standard library. Just, imagine life without printf!
    – Alok Save
    Nov 27, 2011 at 4:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.