Scope of Variable in C Programming

         

  •  Scope:Scope is a region in a program.It is nothing but a region where variable is declared and In that region it can be accessible.In C programming we have three different type of scope based on region where the variable is declared.
  • Types of Scope:

     1.Local variabl

 local variable are defined inside  function and it has local scope.local scope  mean  it is local to that function i.e it can be accessed within that function only.

#include <stdio.h>

void funof()
{
    /*local variable of function funof*/
    int ew = 4;
    printf("%d\n",ew);
}

int main()
{
    /*local variable of function main*/
    int ew = 10;
    {
        /*local variable of this block*/
        int ew = 5;
        printf("%d\n",ew);
    }
    printf("%d\n",ew);
    funof();
}

 

output

1

10

4

2.Global variable 

The 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 this variables are declared, these can be accessed and modified by any function in the program. We can have the same variable name for a local and a global variable but the local variable gets first priority inside a function.           

#include <stdio.h>

/*Global variable*/
int r = 10;

void func()
{
    /*local variable of same name*/
    int r = 5;
    printf("%d\n",r);
}

int main()
{
    printf("%d\n",r);
    func();
}

 

Output

10

5

In above,We can see that the value of the local variable ‘r’ was given first priority inside the function ‘func’ over the global variable have the same variable name ‘r’.

Formal Parameters

Formal Parameters are nothing but the variable which accept the value which is passed during function call.This variable can be used within function only. Formal parameters are treated as local variables in that function and get a priority over the global variables.

#include <stdio.h>

/*Global variable*/
int x = 10;

void fun1(int x)
{
    /*x is a formal parameter*/
    printf("%d\n",x);
}

int main()
{
    fun1(54);
} 

Output

54


If you any have doubt,suggestion regarding this post or website then feel free to share with us.
 
If you have learned something new from this post then share this post with your family and
friends.
 
Happy Learning :)😎   

              

Previous Next

Post a Comment

Previous Post Next Post