C is a beautiful language. Though I have been using it for a few years now, I have yet completely mastered it. Just now, I stumbled across what are called variadic functions.
Have you ever wondered how to write functions that take in variable numbers or arguments? Take for instance printf() or scanf(). Both have been implemented in C. These are called variadic functions.
Problem: To construct a function which can take variable number of inputs, eg; printf()
Solution:
Its a simple matter of using built in macros defined in the stdarg.h library. It provides the following macros:
- va_list: The list of argument
- va_start: Initializes va_list to the first unnamed argument
- va_arg: Takes the current variable and the type
- va_end: Called at the end
Through a self explaining example I would like to demonstrate the usage of these macros. Let us define a new function called PBAPrint() which imitates the printf() function. For example,
PBAPrint(“df”, 12, 2.2) outputs: int = 12 float = 2.2
PBAPrint is implemented as follows:
void PBAPrint(char *format, ...) {
va_list ap;
va_start(ap, format);
while(*format) {
if(*format == 'd')
printf("int = %d ", va_arg(ap, int));
else if(*format == 'f')
printf("float = %f ", va_arg(ap, float));
else {
printf("unsupported format ");
break;
}
format++;
}
va_end(ap);
return;
}
But apparently things are much more simpler when using C++.
Popularity: 3% [?]
Recent Comments