Saturday, March 5, 2011

Use of static variable

use of static variables:

as all of u are familiar with static variables, its a storage class. i am just explaining the use of static variable with the help of an example.

int *f()

{

int i=20;

return(&i);

}

void main()

{

int *ptr;

ptr=f();

printf(“%d”,*ptr);

getch();

}

Its output is 20. but if the program is this

int *f()

{

int i=20;

return(&i);

}

void main()

{

int *ptr;

ptr=f();

printf(“%u”,ptr);

printf(“%d”,*ptr);

getch();

}

I think the output will be some address and 20

But at the place of 20,it has some garbage value…………

Why so………….

But if the storage class of i is static like

int *f()

{

static int i=20;

return(&i);

}

void main()

{

int *ptr;

ptr=f();

printf(“%u”,ptr);

printf(“%d”,*ptr);

getch();

}

Then the output is some address and 20………

Explanation:

When we call any function immediately after calling f() function .then printf(“%d”,*ptr); prints garbage value except 20… in the first case, when control returned from f() though variable i went dead but it was still left on the stack. We then access this value using its address that was in ptr… but when we precede the call to printf by a call to any other function as I did in 2nd printf(“%u”,ptr); printf(“%d”,*ptr); the stack is now changed, hence we get the garbage value…. If we want to get the correct value each time then must declare var i as static . by doing this when the control returns from f(), var i will not die………..

No comments:

Post a Comment

Feel free to comment......