Within-function static variables

May 26, 2015 at 9:49am
May I know what is the use for such variable, as stated in the code below?

1
2
3
4
5
6
7
...
void pencilcase ()
{
    static int x = 10;
    int y = 20;
}
...

I know 'y' gets destroyed when out of scope and not for 'x'. However, I cannot access 'x' outside the 'pencilcase()' function. I understand that by including "static" variable 'x' still exists in memory? Or am I wrong?

Thank you!
May 26, 2015 at 9:54am

static means that x will retain its value once you leave the function... so, for example, if you were to increase x by 1 at the end of the function and go back in it would be 11 not 10.

Take away the static and x would be initialised to 10 each time you call the function.

x and y are local variables and not global, only pencilcase will see and use it unless you return its value.
May 26, 2015 at 1:31pm
In a very real sense x is a global variable -- it exists throughout the entire run of your program in a global data segment and everything; but only the function pencilcase() knows about it.

Hope this helps.
May 27, 2015 at 3:16am
Thanks!
Topic archived. No new replies allowed.