Home > Back-end >  What are the arguments before the variadic arguments?
What are the arguments before the variadic arguments?

Time:12-16

I am confused about the usage of the arguments before ... in c. Some people say that the parameter before the ... is supposed to hold the amount of variadic arguments. However how does that make sense with variadic functions like printf()? Does the amount of characters given equal the the upper limit on how many variadic arguments can be given? For example:

printf("Hey"); // Printf() is passing 4 characters (including the null one).
               // So potentially 4 variadic argument?

Or is the final parameter before ... just used to initialize va_list using va_start?

I thought that the parameter before the ... was used to contain the amount of variadic arguments but how does that work with with printf() then?

CodePudding user response:

The va_arg etc macros have no way to know how many arguments you provide. In case of printf it will parse the format string until encountering a null terminator, count the number of conversion specifiers and then pray that the programmer actually gave it as many arguments as the format string said. If the programmer didn't, then printf will run amok.

This is one of many reasons why variadic functions should be avoided when possible. It is one of the most brittle and dangerous features of the C language.

  • Related