Programming in C

(Barry) #1
Automatic and Static Variables 157

void auto_static (void)
{
static int staticVar = 100;
.
.
.
}


the value of staticVaris initialized to 100 only once when program execution begins.
To set its value to 100 each time the function is executed, an explicit assignment state-
ment is needed, as in


void auto_static (void)
{
static int staticVar;


staticVar = 100;
.
.
.
}


Of course, reinitializing staticVarthis way defeats the purpose of using a staticvari-
able in the first place.
Program 8.15 should help make the concepts of automatic and static variables a bit
clearer.


Program 8.15 Illustrating Static and Automatic Variables


// Program to illustrate static and automatic variables


#include <stdio.h>


void auto_static (void)
{
int autoVar = 1;
static int staticVar = 1;


printf ("automatic = %i, static = %i\n", autoVar, staticVar);

++autoVar;
++staticVar;
}


int main (void)
{

Free download pdf