简体   繁体   中英

In main(), how to get value from a static variable inside another function?

I want to get a value in main() from the functionTwo() .
The functionOne is designed to calculate the sum of the functionTwo() .

Why I cannot use this sentence to pass the j value to int b ?

int b  = functionOne();
 //function 0ne
int functionOne(int x) {
    static int j = 0;
    j = j + x;
    return j;
}

//function Two
void functionTwo() {
    int a = 10;
    for (int i = 0; i < a; i++) {
        functionOne(2);
    }
}

// print the j value of functionOne in main()
int main()
{
    functionTwo();

    //Why I cannot use this sentence to pass the j value to "int b"?
    int b = functionOne();

    cout << "the j value of functionOne in main() is: " << functionOne << endl;
    return 0;
}

That int functionOne(int x) wants a parameter. That is why you cannot get it like you tried.

There is not clean way to do this, no intended way to get the value from a static variable inside a function. You do return it, but calling the function obviously has a side effect on the static variable, which is of course the purpose of this and practically any other static variable in any function.

In this special case you could get the value but not influence the static variables value, by

int b = functionOne(0);

For a more generic solution (for cases where any parameter value has undesired side effects) you should look into the concept of classes in C++. It allows to create objects which have a similar internal value, but also allow to read them out explicitly, without side effects, via "getter" methods. (The details on this were already mentioned in a comment on your question by john, hope they do not mind.)

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