Prototype of printf and implementation
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);
}
Related videos on Youtube
kpagcha
Updated on September 15, 2022Comments
-
kpagcha over 1 year
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.
-
Shafik Yaghmour over 10 years@YuHao thank you, fixed, cppreference usually has matched C documents, I got confused there.
-
luk32 over 10 yearsHaha, implementing
simple_printf
withprintf
=). I actually wonder if the converting functions thatprintf
family uses are accessible, Forscanf
there are things likeato[fli]
but the reverse ... I could not find it. -
Shafik Yaghmour over 10 years@luk32 it is just to demonstrate how it works, the original C++ example looked a little less silly since it uses
std::cout
but is not really functionally different.