0

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.

2
  • 1
    Have you read this SO post ? Commented Sep 16, 2015 at 1:48
  • 4
    You could do that, but it's essentially just a round about way to make a global variable. Commented Sep 16, 2015 at 1:49

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.