Home > Net >  Can the caller not pass the extra arguments to a variadic function in C?
Can the caller not pass the extra arguments to a variadic function in C?

Time:05-21

I have a variadic function:

        void            some_func(
        char            arg1,
        int             arg2,
        char            arg3,
        char            arg4,
        int             arg5,
        char            arg6, ...
        ) 
        {
        /* Do some stuff */
        }

Can I have function calls like the below:

  1. some_func('a', 23, 'c', 'd', 56, 'y', "yahoo"); /* yahoo is extra, but valid */
  2. some_func('a', 23, 'c', 'd', 56, 'y'); /* Nothing extra passed, only 6 args, is this allowed??? */

My concern is point2. Can we not have the extra arguments in the call if the function is variadic?

CodePudding user response:

Can we not have the extra arguments in the call if the function is variadic

Yes, that is the whole point of a variadic function. Any arguments explicitly defined must be given, but any number or type of additional arguments may be passed, including 0.

Section 6.7.6.3p9 of the C standard regarding function declarations states:

If the list terminates with an ellipsis ( , ...), no information about the number or types of the parameters after the comma is supplied.

Given that "no information about the number ... of the parameters after the comma is supplied", that does not preclude 0 additional arguments being passed.

CodePudding user response:

Yes you can. For example good old int printf(const char * restrict fmt, ...) works this way.

printf("Hello world\n");

-- EDIT --

I was not able to find any wording explicitly allowing zero variadic arguments. The best reference I found is an example at https://port70.net/~nsz/c/c11/n1570.html#6.7.6.3p19

EXAMPLE 3 The declaration int (*fpfi(int (*)(long), int))(int, ...); declares a function fpfi that returns a pointer to a function returning an int. The function fpfi has two parameters: a pointer to a function returning an int (with one parameter of type long int), and an int. The pointer returned by fpfi points to a function that has one int parameter and accepts zero or more additional arguments of any type.

Note that the examples are not normative.

  • Related