Storage Class and Scope Example
/* scope_main.c */
/* external functions and variables */
extern void help();
extern long h_1;
/* Global variables */
int g_1; /* Uninitialized: default to 0 */
void help_routine()
{
/* local variable, uninitialized: defaults to undefined */
int h_1; /* Superceeds the declaration of the global h_1 */
h_1 = 10;
printf("We are in the help routine h_1 = %d.\n", 10);
}
int main()
{
printf("Initial g_1 is %ld\n", g_1);
printf("Initial h_1 is %ld\n", h_1);
help_routine();
printf("We are in main and h_1 shouldn't have changed %ld\n", h_1);
help();
help();
help();
return(0);
}
/* scope_help.c */
/* Global variables */
long h_1 = 5; /* Pre initialized */
static long h_2 = 40;
static void help_routine()
{
/* static locals are REALLY global! */
static long h_2; /* Superceeds the declaration of the global h_2 */
h_2++;
printf("local static h_2 is now %ld\n", h_2);
}
void help()
{
h_2++;
printf("global static h_2 is now %ld\n", h_2);
help_routine();
}
Output
Initial g_1 is 0
Initial h_1 is 5
We are in the help routine h_1 = 10.
We are in main and h_1 shouldn't have changed 5
global static h_2 is now 41
local static h_2 is now 1
global static h_2 is now 42
local static h_2 is now 2
global static h_2 is now 43
local static h_2 is now 3
next slide