variables_and_scope
variables_and_scope
Variable Scope
● Scope is a characteristic of a variable that defines
from which functions that variable may be
accessed.
● Local variables can only be accessed within the
functions in which they are created.
int main(void)
{
int result = triple(5);
}
int triple(int x)
{
return x * 3;
}
#include <stdio.h>
int main(void)
{
triple();
printf(“%f\n”, global);
}
void triple(void)
{
global *= 3;
}
Variable Scope
● Why does this distinction matter? For the most
part, local variables in C are passed by value in
function calls.
int triple(int x)
{
return x *= 3;
}
Variable Scope
● Overwrites foo. (Function declarations omitted for
space.)
int main(void)
{
int foo = 4;
foo = triple(foo);
}
int triple(int x)
{
return x *= 3;
}
Variable Scope
● Things can get particularly insidious if the same
variable name appears in multiple functions, which
is perfectly okay as long as the variables exist in
different scopes.
Variable Scope
int increment(int x);
int main(void)
{
int x = 1;
int y;
y = increment(x);
printf(“x is %i, y is %i\n”, x, y);
}
int increment(int x)
{
x++;
return x;
}
Variable Scope
int increment(int x);
int main(void)
{
int x = 1;
int y;
y = increment(x);
printf(“x is %i, y is %i\n”, x, y);
}
int increment(int x)
{
x++;
return x;
}
Variable Scope
int increment(int x);
int main(void)
{
int xm = 1;
int y;
y = increment(xm);
printf(“x is %i, y is %i\n”, xm, y);
}
x is 1, y is 2