0

Consider the following code:

int s= int(sr/nt);
int temp1 = 0; //initialization for the first time case

// the following is the logic for the subsequent cases
int temp2= temp1; // a non-zero value of 's', calculated previously and stored in temp1 is now transferred to temp2
temp1 = s; // currently calculated value of 's' stored in temp1

double moving_average = (temp1+temp2)/2; // not relevant to the problem

My problem is that I require the above code to run a number of times when it is called; and need the previous values of 's' stored in temp1 to transfer it to temp2 in order to calculate moving average.

As I initialize temp1 to zero in the code, it will be executed for the subsequent iterations and I won't get what I need.

Any ideas? Thanks in advance

ecmadeeasy
  • 17
  • 3

3 Answers3

3

You should make it static

static int temp1 = 0;

This will ensure that it is only initialized once and thereafter won't be reinitialized.

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
1

Possible solutions:

  • Move temp1 and its initialization out of the code and pass temp1 to the function ( I am assuming the above code is in a function). The calling code would manage temp1 and ensure it is the same variable passed to the function:

    void moving_average_func(int& a_temp1)
    {
    }
    
    int temp1 = 0;
    moving_average_func(temp1);
    moving_average_func(temp1);
    
  • Make temp1 a static variable so the initialization occurs once only:

    static int temp1 = 0;
    

It is simpler to restart the calculation with the non-static solution and avoids synchronization requirements if multiple threads are using the same code block (as the multiple threads would be accessing the same temp1 in the static solution).

hmjd
  • 120,187
  • 20
  • 207
  • 252
0

You can make temp1 a static variable, such that it retains its value between function calls. This way it will only be be initialized to zero the first time the function is called - note it is automatically initialized to zero (as per the standard), so you don't have to do it explicitly yourself. Example of how it works:

#include <iostream>

using namespace std;

void asd()
{
    static int a=1;
    cout << a << endl;
    a++;
}

int main()
{
    asd(); //outputs 1
    asd(); //outputs 2
    return 0;
}
Community
  • 1
  • 1
BillyJean
  • 1,537
  • 1
  • 22
  • 39