Eri. Eri. - 5 days ago 7
C++ Question

Get return of a function without sending anything

I have a function header:

double countThis(double counter);


Then, in my main I do this:

double test = 10;
countThis(test);


Then comes the function:

double countThis(double counter) {
double counted = counter;
return counted;
}


On the bottom, I have one last function, and here I want to get
double counted
without having to do
countThis(something)
, I just want to get the return from the previous call that was made in main and get the value 10 (counted).

Answer

One way to achieve this sort of persistence is to use a class and define an instance of that class:

struct Counter
{
    double counted;
    double countThis(double counter)
    {
        return counted = counter; // assign counter to counted, and return that value.
    }
};

At the point of use:

int main()
{
    Counter c;
    c.countThis(10);
    // c.counted contains the last value sent to countThis, in this case, 10
}

The instance c is used to persist the value that you pass to countThis.

Comments