Re: Where is a static variable stored?



"Jack" <junw2000@xxxxxxxxx> wrote
I think for a static variable defined out of any functions, i.e., it is
a global variable, it is located in the data segment of the program.
How about a static variable defined within a function? it is a local
variable. Is it located at the stack?

A static local variable is basically a global which is only visible within
one function.
That is a contradiction in terms, but it is how the compiler will treat it
under the bonnet.

As for data segment, only some OSes have such things. When the program
loads, memory does need to be reserved for all the global variables,
including the static locals, which is why you can think of them as local
globals.

Incidentally this has an important effect. Let's say we need 1000 xyz
coordinates

/* dangerous, may overflow stack if you are not careful */
void foo()
{
double coords[1000][3];
}

/* safe, memory will be allocated at load time. But gobbles resources for
other functions */
void foo()
{
static double coords[1000][3];
}
--
Buy my book 12 Common Atheist Arguments (refuted)
$1.25 download or $7.20 paper, available www.lulu.com/bgy1mm


.



Relevant Pages

  • Re: Localized Parameter Directive?
    ... and the program assembles with no errors. ... I use PROC all the time, and don't remember ever having run into this. ... But, then, I use long descriptive names for my global variables. ... LOCALS in different PROCs can use the same names. ...
    (alt.lang.asm)
  • Re: A Brief Look at History
    ... They can simplify the code, and they're more useful than locals because if you have a nicely factored set of support words they can all use the variables, whereas that isn't true of locals. ... Variables are appropriate when they simplify code and to make data available to a collection of words that need to use it. ... The notion that global variables are evil comes from other languages, ...
    (comp.lang.forth)
  • Re: A Brief Look at History
    ... are extremely useful. ... words they can all use the variables, whereas that isn't true of locals. ... wishes to minimize global variables. ... the goal is to simplify the solution. ...
    (comp.lang.forth)
  • Re: Function decorator that caches function results
    ... a crack at a definition: a closure is a function in which some of ... > the variable names refer to variables outside the function. ... the global variables are someone else's locals. ...
    (comp.lang.python)
  • Re: Thread address space...
    ... Data Segment: Only the global variables. ... >address space of parent process, just because its sharing its global ... and that will be true no matter how many threads are ...
    (comp.os.linux.development.system)