Search code examples
cargumentsvariadic-functionsvariadic

How to check number of variable arguments passed to any function?


I have a program where I am defining a new print function to print some data in required format. Am passing variable arguments of both integer and string data types. Before printing string type i want to check whether how many arguments are passed and type of argument. Else if i pass integer by mistake and try to print in string format then i see segmentation fault
Below is my code;

void my_print(int log, int flags,....)
{ 
   /* ----------------------
   ----------------------
   ---------------------- */
}

Before printing my arguments in required format, I want to check the number of arguments passed to this function. Sometimes I pass 5 arguments and sometimes I pass 6 arguments.

So is there any function in C language to check total number of arguments passed to this function?


Solution

  • The concept of variable arguments requires that the number of arguments is otherwise known.
    An example is the format string of printf(), which implies the number without actually giving it.
    You could also simply specify the number in an additional integer parameter before the variable arguments - because afterwards would of course not work, since you'd need to know the number to find the parameter which provides it.