Lifetime and Scope

The difference between lifetime and scope is quite simple.
Lifetime - Refers to how long or when the variable is valid (i.e. how long will it retain its value for).
Scope - Refers to where the variable can be accessed.
The Lifetime is how long the variable retains its value for.
The scope refers to where the variable can be used.

Variable Lifetime

The lifetime of the local variable "imylocal" extends from the moment ProcedureOne is entered to the moment ProcedureOne has finished.
However the local variable "imylocal" still exists when ProcedureTwo is called, it is just out of scope.

Public Sub ProcedureOne() 
Dim imylocal As Integer
   imylocal = 5
   Call ProcedureTwo()
   imylocal = 10
End Sub

Public Sub ProcedureTwo()
'do something
End Sub

Variable Scope

Every variable has a scope associated with it.
This scope refers to the area of code where the variables will be recognised.
Variables (and constants) have a defined scope within the program.
The scope for a variable can either be:
Procedure Level - Also known as a local variable.
Module Level - A private module level variable is visible to only the module it is declared in.
Global Level - A public module level variable is visible to all modules in the project.


Local variables (in different subroutines and functions) can use the same name without any conflict.
Module level public variables (or global) should be prefixed with a "g".
Module level private variables should be prefixed with a "m".

© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext