40 Intermediate C Programming
In the scope marked X (in the comments), a and b are arguments and i is a local
variable. Another scope called Y is created inside of X. Scopes are always nested inside of
each other like this. Variables from outer scopes are still accessible, so scope Y can “see” a,
b, and i. A local variable j is created inside of scope Y and is accessible only inside scope
Y; scope X cannot “see” j.
The following example has three scopes: X, Y, and Z. The arguments a and b in f1
have nothing to do with the arguments of a and b in f2 because they are in different and
non-overlapping scopes: f1 is not nested in f2 or vice versa.
The variable j is in the inner scope, and can only be “seen” between the { and } of the
for loop.
void f1 ( i n t a , int b)1
{2
/* this is a scope , call it X */3
int i;4
for (i = 0; i < a + b ; i ++)5
{6
/* this is another scope , call it Y */7
int j;8
}9
}10
11
void f2 ( i n t a , int b)12
{13
/* this is a scope , call it Z */14
f1 (a + b , a - b) ;15
/* RL A */16
}17
It is legal to create another variable of the same name in an inner scope, like u.
void f1 ( i n t u , int v)1
{2
/* this is a scope , call it X */3
int i;4
for (i = 0; i < u + v ; i ++)5
{6
/* this is another scope , call it Y */7
int j;8
int u; /* shadow variable */9
}10
}11
In the inner scope Y, we create a new variable called u. Please note that Y already has
an argument called u. By adding the type int in front of u, a new variable is created. This
function now has two variables both called u in the overlapping scopes (Y is nested inside
of X). This makes the u in Y a shadow variable of the u in X. These two variables have two
different memory addresses. Modifying the u in scope Y does not change the u in scope
X. Shadow variables are considered bad programming style because they make programs
difficult to understand, and can introduce subtle errors. Consider the following example:
void f1 ( i n t u , int v)1
{2
/* this is a scope , call it X */3