9lessons programming blog
Loading Search
Saturday, October 18, 2008

What is Printf Doing?

The behavior of printf is undefined if there is insufficient no. of arguments for the format string when i am initializing a variable it print variable value, consider this:



main()
{
int a=10;
printf("%d");
}



ANSWER IS 10.

This was asked by one of my friends. he says," it has to do something with segmentation",so the question is of couse logicaly valid..

The correct answer to the question is undefined behaviour.But if you are wondering why the result prints 10, here's a possible explanation (which seems to work for your platform):


1. Local variables are stored on the stack (int a)

2. The arguments you pass to a function are pushed to the same stack

3. Printf sees a "%d", and assumes that an integer argument is avaliable on
    the stack.

4. It reads an integer from the stack, and picks up the variable 'a', and prints
     it Note that the above explanation seems to work on your (and perhaps many
     other) platform. There is no guarantee that this will be the case with some
     other compiler on some other OS. That's precisely why it is called 'undefined
     behaviour'.
Sponsored Links

Share this post

Comments
{ 1 comments }
Madhura Raju said...

Awesome, thanks! I have always wondered..though it's a simple concept.

Post a Comment

Subscribe now!Recent Posts

Categories

Subscribe now!Popular Posts

People Says

@9lessons thank you for the great tutorials, we truly appreciate your contributions to the design community.

Smashing Magazine

Like Me

follow me
products

9lessons labs

9lessons clouds

Android application

Chrome Extension