Sunday, March 3, 2019

Variable arguments in C

Variable arguments can be passed to a function in C. The best example for this is the inbuilt printf function. For printf the first argument is a character array and variable number of arguments after that. This is implemented using macros within the stdarg header. When parameters are passed to a function , its copied to a stack created for that function. va_list and va_arg and va_end are macros which help traverse thru this stack. This is partial implementation of your own printf function.
#include<stdarg.h>
#include<iostream>
using namespace std;
void my_printf(char* format, ...)
{
va_list argp;
va_start(argp, format);
while (*format != '\0') {
if (*format == '%') {
format++;
if (*format == '%') {
putchar('%');
} else if (*format == 'c') {
char char_to_print = va_arg(argp, int);
putchar(char_to_print);
} else {
fputs("Not implemented", stdout);
}
} else {
putchar(*format);
}
format++;
}
va_end(argp);
}
int main()
{
my_printf((char *) "char %c %c", '1', '2');
my_printf((char *) "string %c %c %d", '3', '4', 5);
}