Variable scope and lifespan

Scope -
  • • Refers to where in a program a particular variable is known
  • • Global variables are known in all parts of the source module following their declaration
  • • Local variables are known only within the block (usually a function) in which they are declaration
  • • Local variables are known only within the block (usually a function) in which they are declared
  • • A local variable can have same name as a global variable or local variable declared in a higher – level block, in which case the most local copy is used

Lifespan -
  • • Refers to how long a variable retains its storage
  • • Global variables and local variables declared as static retain their storage through program execution
  • • Level variables declared as automatic are retain their storage only while the block in which they are declared is executing

Global variables -
  • • Defined outside any function, usually before first function definition
  • • Known to all functions after the variable is defined
  • • Memory space is allocated at compile time
  • • If not explicitly initialized, a global variable is set to zeros
  • • Use only when absolutely necessary
  • • Do not use global variables just to avoid learning how to properly pass arguments (using structures, pointers, etc.)
  • •  In the following example, both main and largest refer to the same variables x and y

#include<stdio.h>
int x = 15, y = 20;         /* global variables */
void main ()
{
   int sum;         /*sum is local to main () */
   sum = x+y;
    . . . .
}
void largest (. . .)
{
    int max;
    max;
   . . . .
}

Local variables -
  • • Defined at the beginning of a black, usually a function block but could be any block in {} braces.
  • • Known anywhere within the block
  • • If local variable has same name as global variable or local variable in higher – level block, the most local copy is used.


About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext