Scope of Variables in R Programming
Scope of Variables in R Programming
The location where we can find a variable and also access it if required is called the scope of a
variable. There are mainly two types of variable scopes:
Global Variables
Global variables are those variables that exist throughout the execution of a program. It can
be changed and accessed from any part of the program.
As the name suggests, Global Variables can be accessed from any part of the program.
Global variables are usually declared outside of all of the functions and blocks. They can be
accessed from any portion of the program.
# R program to illustrate
# usage of global variables
# global variable
global = 5
Output
[1] 5
[1] 10
In the above code, the variable ‘global’ is declared at the top of the program outside all of the
functions so it is a global variable and can be accessed or updated from anywhere in the program.
Local Variables
Local variables are those variables that exist only within a certain part of a program like a
function and are released when the function call ends. Local variables do not exist outside the
block in which they are declared, i.e. they can not be accessed or used outside that block.
# R program to illustrate
# usage of local variables
func = function(){
# this variable is local to the
# function func() and cannot be
# accessed outside this function
age = 18
print(age)
}
cat("Age is:\n")
func()
Output
Age is:
[1] 18
1. Scope A global variable is defined outside of any function and may be accessed from
anywhere in the program, as opposed to a local variable.
2. Lifetime A local variable’s lifetime is constrained by the function in which it is defined. The
local variable is destroyed once the function has finished running. A global variable, on the
other hand, doesn’t leave memory until the program is finished running or the variable is
explicitly deleted.
3. Naming conflicts If the same variable name is used in different portions of the program,
they may occur since a global variable can be accessed from anywhere in the program.
Contrarily, local variables are solely applicable to the function in which they are defined,
reducing the likelihood of naming conflicts.
4. Memory usage Because global variables are kept in memory throughout program
execution, they can eat up more memory than local variables. Local variables, on the
other hand, are created and destroyed only when necessary, therefore they normally use
less memory.