Search your topic here

Scope and lifetime of variable


The scope of a vriable is the part of the program for which the declaration is in effect.

In Java, the scope of such a variable is from its declaration to the end of the method.

The lifetime of a variable is the time period in which the variable has valid memory.
In Java, the lifetime of a variable is the period of time beginning when the method is entered and ending when execution of the method terminates.

Types of Scope of a varibale:
  • Local scope: "visible" within function or statement block from point of declaration until the end of the block.
  • Global scope: visible everywhere unless "hidden".
  • Class scope: "seen" by class members.
  • Namespace scope: visible within namespace block.
  • File scope: visible within current text file.
Type with lifetime of variable:
  • Static: A static variable is stored in the data segment of the "object file" of a program. Its lifetime is the entire duration of the program's execution.
  • Automatic: An automatic variable has a lifetime that begins when program execution enters the function or statement block or compound and ends when execution leaves the block. Automatic variables are stored in a "function call stack".
  • Dynamic: The lifetime of a dynamic object begins when memory is allocated for the object (e.g., by a call to malloc() or using new) and ends when memory is deallocated (e.g., by a call to free() or using delete). Dynamic objects are stored in "the heap".


Related topics

Please use contact page in this website if you find anything incorrect or you want to share more information about the topic discussed above.