Prototype of printf and implementation
c, variadic-functions
Solution
how the printf function is declared
printf is a variadic function and it declared since C99 as follows:
int printf( const char *restrict format, ... );
^^^
The `...` or ellipses indicate that there are a variable number of argument and we would use the va_start, va_arg, va_end macros and va_list type to access the arguments.
how is the function implemented?
and example of a very simple printf is given in the document linked above is as follows and modified to work in C:
#include <stdio.h>
#include <stdarg.h>
void simple_printf(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
while (*fmt != '\0') {
if (*fmt == 'd') {
int i = va_arg(args, int);
printf( "%d\n", i ) ;
} else if (*fmt == 'c') {
int c = va_arg(args, int);
printf( "%c\n", (char)c ) ;
} else if (*fmt == 'f') {
double d = va_arg(args, double);
printf( "%f\n", d ) ;
}
++fmt;
}
va_end(args);
}
int main()
{
simple_printf("dcff", 3, 'a', 1.999, 42.5);
}
Problem
I started to wonder how the `printf` function is declared, it always receive a string as first parameter (well, `const char*`) and then the rest of the parameters can be a varierty of types, a variable number of them and given in different order. Does this mean the `printf` function is declared and overridden for each of the possibilities? This does not make much sense to me, so does it really work like this or it's way different? Also, how is the function implemented? If it's too complicated I'd just like to know how it works internally in general.