Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset static variables within a function

Is there a way to reset variables declared as static within a function? The goal is to make sure that the function is not called with lingering values from an unrelated call. For example, I have a function opearting on columns of a matrix.

int foo(matrix *A, int colnum, int rownum){
static int whichColumn;
static int *v; //vector of length A->nrows 
   if (column != whichColumn){
    memset(v,0,size);
    whichColumn = which;
   } 
   //do other things
}

The function is called n times, once for each column. Is this a proper way of "re-setting" the static variable? Are there other general fool-proof ways of resetting static variables? For example, I want to make sure that if the call is made with a new matrix with possibly different dimensions then the vector v is resized and zeroed etc. It seems the easiest way may be to call the function with a NULL pointer:

int foo(matrix *A, int colnum, int rownum){
static int whichColumn;
static int *v; //vector of length A->nrows 
   if (A == NULL){
    FREE(v);
    whichColumn = 0;
   } 
   //do other things
}
like image 805
Sue Avatar asked Aug 15 '10 18:08

Sue


1 Answers

Use an idempotent initializer function and global variables instead.

For example:

int foo;
int *m = NULL;

static void InitVars() {
    foo = 0;
    if (m != NULL) {
        free(m);
    }
    m = malloc(sizeof(int)*5);
    memset(m, 0, sizeof(int)*5);
}

If your initializer is really idempotent, you can call it again to reset the variables.

If you need this to be called automagically, use __attribute__((constructor)) (for GCC) like so:

static void InitVars __attribute__((constructor)) ();

However, you should note that if you need to do this, you should reconsider using in-function static variables and instead use passed-in fresh ones that are returned/written and passed to subsequent related calls.

like image 170
Borealid Avatar answered Oct 16 '22 22:10

Borealid