0

The static vars in a program exists in the memory for all the execution time while the static vars of a subprogram are created (by invocations to the subprogram) and destroyed (by termination of the subprogram) which is done by pushing of the subprogram's activation record onto and popping of it off the program's function call stack, but:

What about the static vars in blocks(I mean control structures or any {} block) inside the main program? They aren't accessible outside their blocks where they are defined, How is memory concept for them?

Are they exist in the memory in the whole program execution but aren't accessible outside their blocks or there are activation records also for every block other than subprograms?

MTVS
  • 2,046
  • 5
  • 26
  • 37
  • [Local scope.](http://msdn.microsoft.com/en-us/library/b7kfh662.aspx) A name declared within a block is accessible only within that block and blocks enclosed by it, and only after the point of declaration. The [static](http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx) keyword. – Serg Jan 09 '13 at 19:55
  • found the answer here: http://stackoverflow.com/questions/2759371/in-c-do-braces-act-as-a-stack-frame and here http://stackoverflow.com/questions/8927086/will-a-new-stack-frame-be-created-on-entering-a-block-of-statements – MTVS Jan 14 '13 at 09:50

1 Answers1

0

Static variables in all cases are allocated once for the lifetime of the program. (I think by "subprogram" in your question you mean a C function.) Your question is specific to the programming language in use, so I'm going to assume C.

The ability of a code block to "see" (or not see) the static variable is separate, and is a fiction enforced by the compiler's lexical scoping rules.

Specifically in C, static variables at global scope, function scope and block scope are all stored once per program for the entire life of the program. In the following example (at least) 3 words will be allocated when the program starts:

static int globalWord;

int aFunction(void) {
  static int aFunctionPrivateStatic;
} 

int main(void) {
   while (1) {
     static int whilePrivateStatic;
     // ...
   }

   // ...
}

See http://en.wikipedia.org/wiki/Static_variable for a more thorough example.

P.T.
  • 24,557
  • 7
  • 64
  • 95
  • ok, but the default storage class for the local vars is automatic, in fact the storage class of the vars in the main also is automatic but they are persistent in the whole execution time. – MTVS Jan 10 '13 at 11:34