I'm new to programming, and am trying to get a better understanding of pointers specifically. Could a static variable be declared inside a function and then accessed or deferenced from outside the function? Why would you not allow explicit pointers to it out of scope, since the memory of the static variable would remain allocated.
-
1Have you read [this SO post](http://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function) ? – Tim Biegeleisen Sep 16 '15 at 01:48
-
4You could do that, but it's essentially just a round about way to make a global variable. – user3386109 Sep 16 '15 at 01:49
2 Answers
Could a
static
variable be declared inside a function and then accessed or deferenced from outside the function?
The language allows it. So, yes, you can access a pointer to it from outside the function and dereference the pointer from outside the function.
Why would you not allow explicit pointers to it out of scope, since the memory of the static variable would remain allocated.
There are risks associated with that. A calling function can change the state of the static
variable. That may or may not be OK depending on the overall structure of your program.

- 204,454
- 14
- 159
- 270
Could a static variable be declared inside a function and then accessed or deferenced from outside the function?
Yes, you can do that.
Explain the scenario where you need this, but in general I don't think its a good approach. Just declare it global.
That question was part of a Homework in Programming 101 when I was in college :)

- 6,846
- 6
- 41
- 73