1

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 ?

2
  • What about kprintf("%d %s", 47, "%u", 11);, should that work like Python's "%d %s" % (47, "%u" % 11) and print 47 11? If so, good luck! :) Commented Feb 20, 2013 at 11:13
  • 1
    What if you write a version that takes in a va_arg pointer (like vprintf does)? Commented Feb 20, 2013 at 11:17

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Bear in mind, that you have to know argument type when you are retrieveing it.
@Losiowaty yep, absolutely true
0

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

Comments

0

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].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.