Calling functions with Static variables

I have a function which does something using a static variable in it . Lets call this "void calledFunction () "

In the main loop, I have atleast four other functions which need to call the " calledFunction()" and in no particular order.

Now every call to the calledFunction() is going to alter the static variable in it. If i dont want this to happen and retain four different copies should I create three more clones of " calledFunction(); ?

Thanks !!

Hello Ardubit
Design a bool variable for the take over of the value inside the function.

void calledFunction (bool takeOver, int value)
calledFunction (takeOver,  value) {
        if (takeOver) staticVariable=value;
}

Have a nice day and enjoy coding in C++.

No.

This is the perfect case for writing your function as a class. Then each instance of the class can have its own static variable, and they are all kept separate.

... or simply pass a ptr to a unique variable to the function. see strtok_r()

If you want each calling function to have its own copy of the static variable, pass the static variable by reference. This allows calledFuntion() to change the value but a different value for each caller.

void caller1()
{
  static int myStaticInt = 0;
  calledFunction (myStaticInt);
}

void caller2()
{
  static int myStaticInt = 0;
  calledFunction (myStaticInt);
}

void calledFunction(int &theStaticInt)
{
  theStaticInt++;
}
1 Like

Thanks @johnwasser for taking the effort to actually make a sample.

Of course there were suggestions to make a class and other tips. But for me those are a bit far fetched.

Thanks to all those who posted in response !!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.