38


Static Variables

A static variable is local to particular function. However, it is only initialised once (on the first call to function).

Also the value of the variable on leaving the function remains intact. On the next call to the function the static variable has the same value as on leaving.

To define a static variable simply prefix the variable declaration with the static keyword.

For example:

void stat(); /* prototype function */

main()

}

stat()

The output is:

auto= 0, static=0

auto= 0, static= 1

auto= 0, static= 2

auto= 0, static= 3

auto= 0, static= 4

Clearly the auto_var variable is created each timethe function is called. The static_var is created once and remembers its value.


drago@scri.fsu.edu
Jan. 1997