Explain about block scope in C ?

devquora
devquora

Posted On: Feb 22, 2018

 

A block is defined as a sequence of statements enclosed between curly braces, { and }. In other words, a block is a compound statement. For example, a function body is a block, because it is simply a sequence of statements enclosed within curly braces. Blocks of statements in if statements and loops. All these blocks of statements actually follow the same rules.

Consider the example shown below, the variable j declared in both main and the user defined function other func. Accessing j uses the local declaration in the called function.

//Illustration of block scope
#include <stdio.h>
void OtherFunc( void )
{
	int i = 10;
	printf(" Inside the function OtherFunc, the value of i is %d\n", i);
}
int main() 
{
  int i = 20;
  printf(" Inside the function main, the value of i is %d\n", i);
  OtherFunc();
  return 0;
}
OutPut: 
Inside the function main, the value of i is 20
Inside the function OtherFunc, the value of i is 10

The variables defined can be accessed only within the block in which they are declared. In cases of nested blocks, the variables declared in the outer blocks are accessible by statements in the inner blocks, and not vice-versa. These variables are called local variables because they are localized to the block. It helps to prevent the integrity of data (data of one function cannot be modified by another function, directly). It can be observed that if two variables of the same name are declared in many functions, they are distinct and unrelated variables. The scope of the variables in the function parameter list is also confined to the function, i.e., they are also local variables.

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    C Programming Interview Questions

    What are static variables in C ?

    C defines another class of variables called static variables. Static variables are of two types:Static variables tha..

    C Programming Interview Questions

    What is a scope resolution operator in C ?

    The scope resolution operator (::) is useful in C programming when both global and local variables have the same name,..

    C Programming Interview Questions

    What is register variable in C language ?

    C language allows the use of the prefix register in primitive variable declarations. Such variables are called register..