Eri.
Eri.

Reputation: 465

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).

Upvotes: 1

Views: 85

Answers (4)

Karl Nicoll
Karl Nicoll

Reputation: 16419

Why not just copy the value into a new instance of double?

Example:

double test = 10;
countThis(test);

double something = test;

Upvotes: 0

user1438832
user1438832

Reputation: 493

You can use global variable.(double counted) and in the function

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

define another function to just return counted

double count() {
    return counted;
}

But,i suggest you to create a struct and make getter and setter on it.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182759

Do this:

double test = 10;
double ret;
ret = countThis(test);
// Now the value returned by countThis is in ret

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234715

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.

Upvotes: 3

Related Questions