See this page as a slide show
CS156 Scope
The Scope of Variables
- All variables in a C program have a scope
that determines where they are accessible.
- For example, variables declared outside the
main
function have global scope.
- We have also seen variables with local
scope declared in the
main
function.
An Example
int glow; // a global scope variable
int main() {
int loco = 1; // a local scope var with
// valid scope in main
glow = 2;
{ // braces introduce a new scope
int engineer; // a variable in this scope
engineer = loco; // accessing a local
glow = 3; // accessing a global
}
engineer = 2; // ERROR: variable not in scope
return 0;
}
Variable Names and Scope
- Variables can have the same names if they are defined in different scopes.
- The variable with the most local scope is active in any given block.
int main() {
int n = 111;
printf("n = %d\n", n);
{
int n = 222;
printf("n = %d\n", n);
}
printf("n = %d\n", n);
return 0;
}
n = 111
n = 222
n = 111
- These are two different variables, each called
n
.
- We can’t access the first
n
within the inner block.
Some Tips on Scope
- Not everything you can do in C, you should do.
- Declaring variables with the same name usually
leads to code that is hard to understand.
- Global variables become hard to manage when
you begin to work with multiple files.
- Declare variables in the smallest, most restrictive,
scope that you can manage.