Re: printf functionality

Posted 11 June 2010 - 01:50 AM

The internal working of printf is implementation defined. Every platform is free to implement it any way they want. At the extreme that means that if a platform existed where printf was actually implemented as an assembler instruction then for that platform the implementation would consist of calling that instruction.

This is true of all library functions, the platform is free to implement them however it chooses and you would really expect the platform makers to have implemented the standard library taking all advantage of the specific facilities of the platform to enhance library performance.

now all that said it is unlikely that printf will ever be implemented as an assembler instruction. I have seen a number of platforms that implement the whole printf family though 1 underlying function that implements the format parsing. If you would like to see 1 implementation to try and understand it then I suggest you download the GNU C Library source code and look it up in there.

Re: printf functionality

Generally speaking printf() does NOT actually display or "print" anything -- it passes this on to the OS to do. Printing is done via the stdout stream (which is generally owned by the OS).

So for example at its base level printf in windows probably does something similar to this snippet I posted a while back in assembly. It uses two OS function GetStdHandle which returns the handle to the standard output, and then WriteFile to actually send the data to the stream.

However that is just a guess -- BUT there is often a way you can find out how YOUR compiler does it! If you have downloaded VS 2010 Beta2 it has the source code for the C Runtime library with it, you can look in the source to see exactly what happens. It should be quite an adventure!

For me the source can be found at: "C:\Program Files(x86)\Microsoft Visual Studio 10.0\VC\crt\src" printf.c leads to vprintf.c which makes a call to outfn which is of type OUTPUTFN which is defined in internal.h -- so maybe you can't actually look at the source code for these internal functions... sorry about that.