Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use the parameters of a function that takes any number of parameters, in C

I've just read: "C void arguments" about the differences between these function definitions in C:

int f(void)

and

int f()

Understanding that the second form means a function returning integer that takes any number of parameters, I wondered how can we actually access and use these unknown parameters?

I'd love to get sample code and explanation.

Also, I know the mechanism of the Varargs in C (with va_arg, va_end, va_start functions) and would be glad to hear about the differences between this mechanism and the f() form mentioned above.

Thank you a lot!

like image 959
Reflection Avatar asked Dec 12 '22 11:12

Reflection


1 Answers

The second version does NOT accept a variable number of parameters, it accepts a fixed (but unspecified) sequence of parameters. In effect, it declares the function, but does not prototype the function. So calls to the function will not be checked for valid types. It's common for the compiler to look at the first call to the function and check other calls against the types found in the first call.

This is why, if you omit #include <stdio.h>, the first call to printf will be acceptable, but any calls to printf with different types will generate an error. Eg.

int main() {
    printf("hello");        //<--- accepted, compiler may assume `int printf(char *);`
    printf("%s", "world");  //<--- error, type mismatch
}

To have a function accept a variable number, it must have at least one fixed parameter, and then the token ....

int f (int first, ...);

You will need to include the stdarg.h header file. And the function can access the parameters using macros.

void f (int c,...){
    va_list ap;
    va_start(ap, c);
    for(;c--;)
        printf("%d", va_arg(ap,int));
    va_end (ap);
}

It's convient to have the fixed argument be a count of the remaining arguments. You'll also need to determine the type of each argument somehow. In this example, they are assumed to all be int.

like image 186
luser droog Avatar answered Dec 28 '22 09:12

luser droog