Scope of Local and Global Variables in C Programming

The scope of variables refers to that portion of the program where the variables can be accessed. They are accessible in some portion of the program and in the other they are not accessible. Scope of a variable defines the portion of the program in which the set of variables can be referenced and manipulated.

When a variable is required in a program, it can be declared as:

  • Local variable
  • Global variable

Local Variables in C Programming Language

  1. The variables that are declared inside a function are called as local variables
  2. The scope is only within the function in which they are declared
  3. Local variables cannot be accessed outside the function in which it is declared
  4. Local variables exist in the memory only till the function ends
  5. The initial values of local variables are garbage values

In the above example,
Variables iNumber1 and iNumber2 are local to function main
Variable iResult is local to function fnSumPrint

Global Variables in C Programming Language

  1. The variables that are declared outside all the functions (Ex: above main()) are called as global variables
  2. These variables can be accessed by all the functions
  3. The global variables exist for the entire life-cycle of the program
  4. The global variables are initialized to default value
  5. Coding Standard for defining global variable:
    Each global variable should start with the alphabet g
    Example:
    int giValue;
    float gfSalary

giNumber1 and giNumber2 are global variables
Variable iResult is local to function fnSumPrint

Difference between Local and Global variables

Variable Scope Value after declaration
Local Variable Can be referenced only within the function in which it is declared Garbage value
Global Variable Can be referenced in all the functions Default values

Disadvantages of Global Variables

  • Lifetime of global variables is throughout the program. Hence usage of global variables leads to wastage of memory
  • Scope of the global variable is throughout the program. Hence more than one function can modify the value of the global variable. This makes debugging difficult.

How long do variables last?
By default, local variables (those declared within a function) have automatic duration: they spring into existence when the function is called, and they (and their values) disappear when the function returns.
Global variables, on the other hand, have static duration: they last, and the values stored in them persist, for as long as the program does. Of course, the values can in general still be overwritten, so they don’t necessarily persist forever.

What is the output of the following code?

The output:

You may also like...

1 Response

Leave a Reply

Your email address will not be published. Required fields are marked *