Function maintains internal state in C

Viewed 220

How can a function in C maintain it's internal state?

For example strtok() - when calling strtok(NULL, del) the function continue working on a previous string.

2 Answers

It contains internal variables to keep track of things, declared as static. This is also the very reason why such functions aren't safe to use in multi-threaded programs.

This is done by declaring local variables as static:

unsigned int some_state_function( void )
{
  static unsigned int internal_state = 0;  // keeps track of the number 
  ...                                      // of times the function has been
  return internal_state++;                 // called - useless, but illustrative
}

The variable internal_state has static storage duration, meaning storage for it is allocated and initialized at program startup and held until the program terminates; its lifetime extends beyond the lifetime of the function. In this case the initialization is redundant (static objects are initialized to 0 or the equivalent), but it's there to illustrate the concept - the initialization occurs once, at program startup, not when the function is called.

However, the identifier internal_state is local to some_state_function - it's not visible outside the function.

strtok does something similar - it has a local static pointer that keeps track of the string you're processing.

Related