Scope Rules in C
Written by
Scope Rules in C:
Scope rules in C or scope of a variable means that from where the variable may directly be accessible after its declaration.
The scope of a variable in C programming language can be declared in three places :
Scope | Place |
---|---|
Local Variable | Inside a function or block |
Global variable | Outside of all function(can be accessed from anywhere) |
Formal Parameters | In the function parameters |
Local variable: Local variables are the variables that are declared inside a block or a function.
These variables can only be used inside that block or function.
Local variables can’t be accessed from outside of that block or function.
Example :
#include <stdio.h>
int main()
{
/* Declaration of local variable */
int a;
/* initialization */
a = 7;
printf (“value of a = %d\n”, a);
return 0;
}
Output :
value of a = 7
Global Variable: Global variable is the variable that is declared outside of a block or function. These variables can be accessed from anywhere in the program.
Once a global variable is declared you can use it throughout your entire program.
Example :
#include <stdio.h>
/* Declaration of global variable */
int a;
int main()
{
/* initialization */
a = 7;
printf (“value of a = %d\n”, a);
return 0;
}
Output :
value of a = 7
Formal parameter: Formal parameters are the parameter that are written in the function definition.
Formal parameter takes precedence over global variable.