How do printf and scanf actually works behind the scene ??


The source code for the GNU C standard library implementation of vprintf (which is called by printf) should indicate that it is not a simple operation with a single answer, however, understanding printf works will reveal a lot about the intricacies of languages in general.

In the theoretical sense, the formatting parameters used by printf and scanf, and other related functions, can be defined using a model called a Context Free Grammar, which is a means of formalising the rules of computer languages, including the C language itself. Due to the simplicity of the the language it is probably not often implemented this way but it may be helpful to use this as a starting point to understand the processes involved.

Technically speaking, printf implementations make use of the va_arg function to be able to read a variable number of arguments passed to the function. Use man va_arg from the command line to see how this might be used. Internally, va_arg (and related functions) are just fetching the function arguments off the stack.

There is also some form of loop which reads each character from the format string and translates the input arguments into the final output string. The process of reading and interpreting the characters in the string is called "parsing" (wikipedia entry). Again, this is a broad subject with well defined theory and solutions.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .