Scope of variable

‘{}’ is called a block. In a C program you can use as many blocks as you wish.Every block can be treated as a single statement. For example:

There are two blocks (block1 and block2) and 3 variable named variable1(outside block2), variable2(inside block2 and outside block1) and variable3(inside block1). Think these 3 variables as 3 persons.
Here block1 exists inside block2. Now imagine block1 as a country named Bangladeshblock2 as  Asia continent and the outside of the block2 as Globe. Now imagine there is a system to gain citizenship of a country or a continent or a glob. Mr. variable1 gains citizenship of the glob, so he can access all rights of any continent and any country.In our example Mr. variable1 can access block1,block2 and outside of block2. Mr. variable2 gains the citizenship of Asia continent. So he can access all rights of Asia continent and Bangladesh.In our example Mr. variable2 can access block1 and block2. Mr. variable3 gains citizenship of Bangladesh. So he can access all rights of Bangladesh only. In our example Mr. variable3 can access only block1.

You can use this blocks in C programming in the same manner and declare variable in any block. If you type the above blocks in C program, you can treat ‘variable1’  as a variable which is declared globally, ‘variable2’ is another variable which is declared as local in block2 and ‘variable3’ is another local variable in block1. You have declared ‘variable1’ as a global variable, so you can use it anywhere of the program. But you can use ‘variable2’ inblock2 & block1 and ‘variable3’ can be used only in block1.

Now look at the programs given below:

OUTPUT

variable1=100

OUTPUT

variable2=10

This program will show an error massage, because ‘variable3’ isn’t accessible in this block.


Next Previous