Psyphy
Psyphy

Reputation: 35

Change local variable in a function from main scope without using global variables

I have a function in my code of the type:

double f (double x, double y){
...
int entry_1 = 0;
int entry_2 = 1;
...
}

The values for entry_1 and entry_2 will change after some loops inside the function f. The function f will be used in the same way in the main script:

double f_value;
double y_instance = 0.5;
for (int i = 0; i<100; i++){
 ...
f_value = f(x*i, y_instance);
...
}

Let's suppose that after this loop, entry_1 = 7 and entry_2 = 0, because they changed inside the f function.

If entry_1 and entry_2 were global variables, now I would do something like this:

entry_1 = 0;
entry_2 = 1;

for (int i = 0; i<100; i++){
...
f_value = f(x*i-2, y_instance);
...
}

I don't think is a good idea to set entry_1 and entry_2 as input parameters, because I would be forced to pass some value during the for loops in the main function. I want that entry_1 and entry_2 are manipulated by f during the for loops, and after those loops, reinitialize them from the main function.

Upvotes: 1

Views: 416

Answers (2)

Robert Andrzejuk
Robert Andrzejuk

Reputation: 5222

You can turn them into parameters of the function. But instead of by copy, take them by reference :

double f (double& entry_1, double& entry_2, double x, double y)
{ ...... }

That way they can be stored wherever You want, but will retain the modifications between calls of the function.

But a better way would be for it to be private variables of a class.

Upvotes: 0

Jeffrey
Jeffrey

Reputation: 11400

You could use a class, and make your program object-oriented:

class Foo
{
  public:
    double f (double x, double y)
    {
        return x + y + entry_1; // for example.
    }
    void setEntry1(double value)
    {
        entry_1 = value;
    }
  private:
    double entry_1 = 0;
    double entry_2 = 1;
};

You then use it like that:

Foo object;
object.setEntry1(0.5);

double z = object.f(0.1, 0.2);
double z1 = object.f(0.2, 0.3);

That allows you to have multiple object performing f with different entry values. And to change those entry values.

Upvotes: 2

Related Questions