What is local and global variables?

  • Local variable is the variable declared and used inside the procedure by default. That means no outside modules have access to it or even know it exits. Value of local variable destroy when program flows out of procedures. 
  • A variable which is declared inside a module and can not be accessed by other modules is known as local variable. The local variable can be used within the module where it it defined. 
Example:SUB sum (a, b)
    c = a +b
    PRINT "Sum of two numbers = "; c
END SUB


  • Global variable is the variable that can be accessed from any procedure or module used on the program. The life of the variable is on whole program and is not destroyed during the execution of the program.
  • They are declared with the keyword SHARED, DIM SHARED, COMMON SHARED. 
A variable declared in a COMMON or DIM statement with the SHARED attribute is global variable to module.

Example:
COMMON SHARED X,Y
DIM SHARED N(5)

Here, the variables X and Y are made global variables as well as array variable N which can store 5 different values are also made global. COMMON SHARED statement is a non-executable statement so it should be written before any executable statement in the program.






Example:
DECLARE SUB average ( )
DIM SHARED n(5)
CLS
FOR i = 1 TO 5
    INPUT "Enter a number"; n(i)
NEXT i
CALL average
END

SUB average
FOR i = 1 TO 5
    s = s + n(i)
NEXT i
a = s / 5
PRINT "Average of numbers ="; a
END SUB

In the above program, as the array variable n has been declared as global variable, it is accessible in SUB procedure 'average' without passing n as parameter from calling program.

Share :

Twitter

Random Posts

Back To Top

facebook main

counter

Powered by Blogger.