Thursday, 17 October 2013

Scope of Identifiers in a Function

Scope of
Identifiers

An 'Identifier' means any name that
the user creates in his/her program. These names can
be of variables, functions and labels. Here the scope of an identifier
means its visibility. We will focus Scope of
Variables in our discussion.

Suppose we write the function:

void func1() {

int i;

…….. //Some other lines of code

int j = i+2; //Perfectly alright

. . .

}

Now this variable ‘i’ can be used in any
statement inside the function func1(). But consider this variable being used in
a different function like:

void func2() {

int k = i +
4; //Compilation error

. . .

}

The variable ‘i’ belongs to func1() and
is not visible outside that. In other words, ‘i’ is local to func1().To
understand the concept of scope further, we have to see what are Code Blocks?
A code block begins with ‘{‘ and ends with ‘}’.Therefore, the body of a
function is essentially a code block. Nonetheless, inside a function there can
be another block of code like 'for loop' and 'while loop' can
have their own blocks of code respectively. Therefore,
there can be a hierarchy of code blocks.

A variable declared inside a code block
becomes the local variable for that for that block. It is not visible outside
that block. See the code below:

void func() {

int
outer; //Function level scope

.
. .

{

Int inner; //Code block level scope

inner
= outer; //No problem

. . .

}

inner ++; //Compilation error

}

Please note that variable ‘outer’ is
declared at function level scope and variable ‘inner’ is declared at block level scope.

The ‘inner’ variable declared inside the
inner code block is not visible outside it. In other words, it is at inner code
block scope level. If we want to access that variable outside its code block, a
compilation error may occur.