Write your own printf() function in c

Write your own printf() function in c

I was wondering where I can find the C code that’s used so that when I write printf(“Hello World!”) in my C program to know that it has to print that string to standard output(i.e. monitor screen). I looked in <stdio.h>, but there I could only find its prototype int printf(const char *format, …), but not how it looks like internally.

Then i start googling for that but i hardly find a solution for which i am looking for. So after long time spend on net, i found this nice formal C Program.

Before implementation of printf( ) function we have to deal with unusual problem which is variable arguments. As we know that printf can take many arguments besides string, like


Write your own printf() function in c


So we have to use a standard library called stdarg.h to handle this variable argument problem. In this implementation context, we don’t need learn whole stdarg.h library because we use some macro functions of these library which is understandable directly by our C program.

Code to implement printf( )




Module 1: Initializing Myprintf’s arguments

In this section, we initialize the arguments of Myprintf( ) function by using standard argument library.


This line declares a variable, arg, which we use to manipulating the argument list containing variable arguments of Myprintf( ). The data type of the variable is va_list, a special type defined by <stdarg.h>.

This line initializes arg variable with function’s last fixed argument i.e. format. va_start() uses this to figure out where the variable arguments begin.

Module 2: Fetching and executing arguments


va_arg() fetches the next argument from the argument list. The second parameter to va_arg() is the data type of the argument we expect. 

Note: va_arg( ) function will never receive arguments of type char, short int, or float. va_arg( ) function only accept arguments of type char *, unsigned int, int or double.

Module 3: Closing argument list to necessary clean-up

Finally, when we’re finished processing the all arguments, we call va_end(), which performs any necessary cleanup.

Original standard printf( )

Here’s the GNU version of printf… you can see it passing in stdout to vfprintf:


Here’s a link to vfprintfall the formatting ‘magic’ happens here.

This is the same thing as we use varargs(stdarg.h library) to get parameters in a variable argument list. Other than that, they’re just traditional C.

Limitation of standard variable argument functions is described in another post named “How can I write a function that takes a variable number of arguments ? ”  which you can see below in suggested reading.


  1. http://www.eskimo.com/
  2. http://sourceware.org/
  3. http://stackoverflow.com/
  4. https://www.google.com/

Suggested Reading

  1. C/C++ program to shutdown or turn off computer
  2. Function Pointers in C/C++
  3. How can I write a function that takes a variable number of arguments?