user2869179
user2869179

Reputation: 13

Why can a static class variable not be allocated to the stack?

Normally, a local variable declared in a function is allocated on the stack, not on the heap, but this is not the case if the variable is static. Why can a static class variable not be allocated on the stack?

Upvotes: 0

Views: 182

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409482

The lifetime of a local static variable is the whole of the program, but the stack is used, reused and reused again over multiple function calls, by all functions. Therefore static local variables can't be stored on the stack together with the other local variables.

Upvotes: 1

ScottMcP-MVP
ScottMcP-MVP

Reputation: 10425

Variables allocated on the stack are automatically deleted. You don't want a static variable to be deleted.

Upvotes: 2

user207421
user207421

Reputation: 311052

Because then it wouldn't be static. Your question embodies a contradiction in terms.

Upvotes: 3

Related Questions