Facebook   Tumblr   LinkedIn

Variable scope in C


walden systems, Ames Computers, geeks corner, programming, languages, C, variable, define, declare, extern, null, scope, global, local, function

A scope is a region of a program. Variable Scope is a region in a program where a variable is declared and used. So, we can have three types of scopes depending on the region where these are declared and used. Local variables are defined inside a function or a block. Global variables are outside all functions. Parameters are defined in function parameters.

Local variables

Variables that are declared inside a function or a block are called local variables and are said to have local scope. These local variables can only be used within the function or block in which these are declared. We can use a local variable only in the block or function in which it is declared. It is invalid outside it. Local variables are created when the control reaches the block or function containing the local variables and then they get destroyed after that.

1   #include 
2
3   void func1()
4   {
5       int x = 5;
6       printf(": %d ",x);
7   }
8
9   int main()
10  {
11      int x = 10;
12    {
13        int x = 15;
14        printf("%d ",x);
15    }
16    printf(": %d ",x);
17    func1();
18  }


The above code will output 15 : 10 : 5



Global Variables

Variables that are defined outside of all the functions and are accessible throughout the program are global variables and are said to have global scope. Once declared, these can be accessed and modified by any function in the program. We can have the same name for a local and a global variable but the local variable gets priority inside a function.

1  #include 
2
3  int x = 10;
4
5  void func1()
6  {
7      int x = 5;
8      printf(" %d",x);
9  }
10
11 int main()
12 {
13     printf("%d :",x);
14     func1();
15 }


The above code will output 10 : 5

Function parameters

Function parameters are the parameters which are used inside the body of a function. Formal parameters are treated as local variables in that function and get a priority over the global variables.

1  #include 
2
3  int x = 10;
4
5  void func1(int x)
6  {
7      printf("%d",x);
8  }
9
10 int main()
11 {
12     func1(5);
13 }


The code above will output 5