0

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?

Karma Yogi
  • 615
  • 1
  • 7
  • 18

2 Answers2

1

By definition (read the C11 standard n1570) any variadic function (such as printf) should know when to stop fetching arguments : see stdarg(3).

The usual way is to have a discriminating prefix argument (like syslog(3) does). You could have other conventions (e.g. store in some global variable something describing the call, use C macros, etc...).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

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.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54