Search code examples
c++functionvariablesglobal-variables

share variable between functions


#include <iostream>

using namespace std;

void lemo(){
    int shamble;
}

int main(){
    lemo();
    shamble= 2;
    cout<<shamble;
    return 0;
}

All I want is call a variable from other function. After executing console will say:

'shamble' was not declared in this scope

What can I do for this problem?

Use variable and list of objects in other files and functions.


Solution

  • Your compiler is correct. shamble was not declared within the scope of main. As it stands your lemo function does nothing. It declares an unused local variable and then exits.

    You could just as well write the following, and it would actually compile.

    #include <iostream>
    
    int main() {
        int shamble = 2;
        std::cout << shamble;
        return 0;
    }
    

    If you want a variable to be available to multiple functions, it can be declared "globally" but don't. This rapidly leads to code that is difficult to reason about and troubleshoot.

    Rather you should pass information from one function to another via arguments and return values. Or you may wish to encapsulate that persistent state into objects.