Wednesday, November 18, 2020

Scope of Variable

A scope is a region of the program, and the scope of variables refers to the area of the program where the variables can be accessed after its declaration.

There are two types of scopes depending on the region where these are declared and used –


  1. Local variables are defined inside a function or a block

  2. Global variables are outside all functions

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.

Local variables are created when the control reaches the block or function contains the local variables and then they get destroyed after that.

 #include <stdio.h>

void fun1()

{

    /*local variable of function fun1*/

    int x = 4;  

printf("%d\n",x);

}

int main()

{

    /*local variable of function main*/

    int x = 10;

    {       

/*local variable of this block*/

      int x = 5;     

printf("%d\n",x);

    }  

printf("%d\n",x);

    fun1();

}


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.

#include <stdio.h>

/*Global variable*/

int x = 10;

void fun1()

{

    /*local variable of same name*/

    int x = 5;

    printf("%d\n",x);

}


int main()

{

    printf("%d\n",x);

    fun1();

}

Scope rules in C

C scope rules can be covered under the following two categories.

There are basically 4 scope rules:


        SCOPE



                                           MEANING



File Scope



Scope of a Identifier starts at the beginning of the file and ends at the end of the file. It refers to only those Identifiers that are declared outside of all functions. The Identifiers of File scope are visible all over the file Identifiers having file scope are global


Block Scope



Scope of a Identifier begins at opening of the block ‘{‘ and ends at the end of the block ‘}’. Identifiers with block scope are local to their  block


Function Prototype Scope



Identifiers declared in function prototype are visible within the prototype



Function scope



Function scope begins at the opening of the function and ends with the closing of it. Function scope is applicable to labels only. A label declared is used as a target to goto statement and both goto and label statement must be in same function


0 comments:

Post a Comment

Data Structures with C++



NET/SET/CS PG



Operating Systems



Computer Networks



JAVA



Design and Analysis of Algorithms



Programming in C++

Top