Connecting Tech Pros Worldwide Forums | Help | Site Map

how printf() statement executes internally

Newbie
 
Join Date: Jul 2008
Posts: 1
#1: Jul 22 '08
thanks for your time

Any body please explain the actual mechanism performed while executing the printf()( with the help of stack if possible )

eg: printf("%d%d",a++,--a,a--);
Banfa's Avatar
AdministratorVoR
 
Join Date: Feb 2006
Location: South West UK
Posts: 6,165
#2: Jul 22 '08

re: how printf() statement executes internally


The actual mechanism is implementation and therefore platform dependent. Many embedded platforms have at least 2 available implementations one with and one without floating point support as this adds rather a lot of code to the binary image.

If you would like to see an implementation of printf then try Googling printf source code and looking at one.

In general printf uses a pointer to scan down the format string copying characters to the output stream. When it encounters a format code (%...) then it executes additional code to extract a value from the stack format it in the correct manor according to the format code and send it to the output stream.

It is not possible to say what your code example prints because it invokes undefined behaviour because if modifies the value of a more than once between sequence points. As soon as undefined behaviour is invoked all bets are off, anything could happen.
Needs Regular Fix
 
Join Date: Jul 2008
Posts: 381
#3: Jul 22 '08

re: how printf() statement executes internally


Quote:

Originally Posted by Krishnam

thanks for your time

Any body please explain the actual mechanism performed while executing the printf()( with the help of stack if possible )

eg: printf("%d%d",a++,--a,a--);

(let's suppose there are 3 %d's, not 2 ) first of all, it's bad code and result of it is undefined - it depends on how compiler decide to evaluate argument for function - left to rigth or right to left.
googling pattern - sequence point

As for this code ( besides 'what a is equal to after all this' ) it looks like the following( assuming all arguments are passed on stack that is not always true )
it places, say, address of string, then a, a-1, a in 4 consecutive say, 4-bytes locations on stack and calls printf. Then printf, knowing address of first argument (char*) iterates over 3 other using va_arg knowing arguments' size given in format string ( %d -say, 4 bytes ) I.e. address of second argument is (address of first) - 4.
Moderator
 
Join Date: Mar 2007
Location: North Bend Washington USA
Posts: 5,366
#4: Jul 22 '08

re: how printf() statement executes internally


The law is that a variable cannot be modified more than once in the same sequence point. That is, more than once in the same expression. When you do, the results are indeterminate (that is, rthey vary by compiler).

Don't ever do this and you will go craze trying to make a rule for indeterminate behavior.
Reply