Functions with a variable number of parameters using (...)

Submitted on: 1/2/2015 4:11:00 AM
By: Derick Dong (from psc cd)  
Level: Intermediate
User Rating: By 3 Users
Compatibility: C++ (general), Microsoft Visual C++
Views: 1016
     To demonstrate how to create a function with a variable number of parameters, similar to the printf function. *Just fixed this, so now you can actually read it.

Somebody asks me how to do something like this,
so I'm posting it. Basically, its a function like
printf, that can take a variable number of
arguments, using the (...). I use something like
this to create a string for my graphics programs,
and draw the resulting string to the screen.

// Create a string function
void CreateAString(const char *format, ...)
va_list list;
char string[1024];

// Create the string from the parameters
va_start(list, format);
vsprintf((char *)string, format, list);

// Function to draw the string goes here

Now, the complete string is stored in 'string'.
To use this function, you can use something like:

void function()
int num1 = 10, num2 = 20;
CreateAString("NUM1 = %d NUM2 = %d", num1, num2);

And 'string' would be:

NUM1 = 10 NUM2 = 20

Pretty easy. Not used real often, but it can be useful.

Other 7 submission(s) by this author


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Intermediate category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)

Other User Comments

 There are no comments on this submission.

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)

To post feedback, first please login.