What is Block Scope in C?

A Block in C is a set of statements written within the right and left braces. A block may contain more blocks within it, i.e., nested blocks.

The right and left braces are as follows:

Right and Left Braces

A variable declared within a Block has a Block Scope. This variable is accessible anywhere within the block and its inner blocks. Hence, the scope of such a variable ends where the block ends.

Examples

The following code shows an example of a single block. The variables a and b are accessible within the block. Hence, we can successfully display their values inside the block, as shown below:

#include <stdio.h>
int main() {
// Block
{
//Variables within the block
int a = 8;
int b = 10;
printf ("The values are: %d, %d\n", a, b);
}
return 0;
}

The following example shows a nested block:

  • Variable a (declared within the outer block) is accessible by the outer and inner blocks.

  • Variable b (declared within the inner block) is accessible by the inner block only since its block scope is limited to the inner block only, as shown in the code below:

#include <stdio.h>
int main() {
//Outer Block
{
int a = 10;
//Inner Block
{
int b = 20;
printf ("The value of a is: %d\n", a);
printf ("The value of b is: %d\n", b);
}
printf ("The value of a is: %d\n", a);
}
return 0;
}
Copyright ©2024 Educative, Inc. All rights reserved