简体   繁体   中英

how to reset function's static variable in c++

when you try to use the following function for the first time it will give you correct answer which gives you the LCM of two numbers ( Least common multiple ). for the second call with new parameters the static variable wont be starting at 1 which is going to give me wrong answer. is there anyway to set it up to 1 before doing his recursive loop ?

int lcm(int a, int b)
{ 
    static int common = 1;

    if (common % a == 0 && common % b == 0)
        return common;

     common++;
     lcm(a, b);
     return common;
}

There is no built-in language mechanism for resetting function-level static variables. Although you can built your own way of communicating the need to reset the static to its initial value, it would remain a poorly-readable abuse of the language.

In particular, you should never use static variables in recursive functions, because non-reentrant recursive functions are nearly useless. In addition, your recursive implementation is painfully slow, because it tries candidate lcm s sequentially one by one. Feeding it two reasonably large prime numbers would result in stack overflow.

Rewrite your recursive lcm in a way that does not use static .

You should not use static variables for such a case. Use it as a parameter:

int lcm(int a, int b, int &common)
{ 
  if (common % a == 0 && common % b == 0)
    return common;

  common++;
  lcm(a, b, common);
  return common;
}

// now you can also overload it to avoid using argument:
int lcm(int a, int b)
{
    int common = 1;
    return lcm(a, b, common);
}

With static variable, you also break the thread-safety of the function. You would have to make sure only one thread is calling it.

EDIT

If you change the function a little bit:

int lcm(int a, int b, int common = 1)
{ 
   if (common % a == 0 && common % b == 0)
      return common;

   return lcm(a, b, ++common);
}

Now you don't need the common to be a reference and it's much simpler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM