c++global-variablesscope-resolution-operator

How can i access global symbol using function in c++?


I want to access the value assigned to global variable in main function from the function. I don't want to pass argument in function.

I have tried referring different stack overflow similar questions and C++ libraries .

#include <iostream>

long s;  // global value declaration

void output()  // don't want to pass argument
{
    std::cout << s;
}

int main()
{
    long s;
    std::cin >> s;  // let it be 5
    output()
}

I expect the output to be 5 but it shows 0.


Solution

  • To access a global variable you should use of :: sign before it :

    long s = 5;          //global value definition
    
    int main()
    {
        long s = 1;              //local value definition
        cout << ::s << endl;     // output is 5
        cout << s << endl;       // output is 1
    }
    

    Also It's so simple to use global s in cin :

    cin >> ::s;
    cout << ::s << endl;
    

    Please try it online