Peter
Peter

Reputation: 11

C - passing variable arguments

I'm writing essentially an implementation of printf. I want it so you can pass many strings within strings, e.g.:

kprintf("Hello %s", "Goodbye %s", "Farewell\n");

Don't ask why, it may very well be insane. Anyway, it recursively calls itself after looking for how many % characters are in the string it is passing; so if more than one % is in it, it should pass many arguments. However, I've been unable to achieve this with any elegance, see the below one:

case 1:
    kprintf(str, argus[0]);
break;
case 2:
    kprintf(str, argus[0], argus[1]);
break;
case 3:
    kprintf(str, argus[0], argus[1], argus[2]);
break;
case 4:
    kprintf(str, argus[0], argus[1], argus[2], argus[3]);
break;
case 5:
    kprintf(str, argus[0], argus[1], argus[2], argus[3], argus[4]);
break;

With argus as an array of pointers. This works, but I hate it. Is there a way to pass variable arguments to a function ?

Upvotes: 1

Views: 331

Answers (3)

Mats Petersson
Mats Petersson

Reputation: 129314

While it would be possible to write something that parses %<something> inside the strings passed to %s, it is generally not how it is done in C/C++.

If you want to put a formatted string into a printf statement, you use sprintf() to format the first string (in a temporary buffer), then pass that string to the actual printf function. Yes, that involves an extra step, but it makes the code much easier - if you are parsing strings passed into printf, you pretty much would have to make printf recursive [or have some sort of stack inside the printf, to track what you are doing].

Upvotes: 0

bash.d
bash.d

Reputation: 13207

There is a type to do your work. It is called "va_list" and you can feed it with arguments (4096 at most, I guess). In order to use it, include starg.h-header and you'll need to use ellipses ... in your function declaration.

int kprintf(int count, ...){
va_list vl;
va_start(vl,count);
for (i=0;i<n;i++)
{
val=va_arg(vl,double);
printf (" [%.2f]",val);
}
va_end(vl);
}

See here for an example.

Upvotes: 3

888
888

Reputation: 3396

If you can use C++, here you can find an article about variable argument functions, with downloadable source code, which should solve your problem.

Upvotes: 0

Related Questions