Tuesday, February 15, 2011

Question on printf

What is the output of the following program?????????
void main()
{
int i=60,j=80;
printf("%d:%d");
}

Output:
80:60

Explanation:
As we have seen that All automatic variables and constants are stored into stack area in the data segment ..
so when we initialize the variables i and j they goes int the stack's initialized area...and printf pops the value from the stack if no 2nd argument is specified....and all we know that stack is LIFO so value 80 is printed before the 60.....

Now take a look at this:
void main()
{
int i=60,k,j=80;
printf("%d:%d:%d");
}

Output:
80:60:garbage value

Explanation:
This is again a bit tricky...we expect the result to be 80:garbage:60 which is not ..........
as we have seen that there are two portions in the stack area in the data segment one for intialized vaiables and other for uninitialized vaiables,and initialized variables lie above the uninitialized variable in the stack....as in the example k is not initialized it goes into the uninitialized area and comes out at the end..........