Skip to content
thesarfo

Note

C: Variable Scopes

Local vs. global variables in C, and how nested blocks can shadow an outer variable.

views 0
/* LOCAL VARIABLES */
int main(void)
{ /* start of basic block */
int a = 5; /* local to main() */
if (a != 0) {
int b = 10; /* local to if basic block */
a = b; /* perfectly legal--both a and b are visible here */
}
int b = 12; /* ERROR -- b is not visible out here--only in the if */
{ /* notice I started a basic block with no statement--this is legal */
int c = 12;
int a; /* Hey! Wait! There was already an "a" out in main! */
/* the a that is local to this block hides the a from main */
a = c; /* this modified the a local to this block to be 12 */
}
/* but this a back in main is still 10 (since we set it in the if): */
printf("%d\n", a);
return 0;
}
/* GLOBAL VARIABLES */
#include <stdio.h>
/* this is a global variable. We know it's global, because it's been declared in "global scope", and not in a basic block somewhere */
int g = 10;
void afunc(int x)
{
g = x; /* this sets the global to whatever x is */
}
int main(void)
{
g = 10; /* global g is now 10 */
afunc(20); /* but this function will set it to 20 */
printf("%d\n", g); /* so this will print "20" */
return 0;
}