Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 614
sahil arora Avatar asked Oct 25 '25 00:10

sahil arora


2 Answers

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


You are declaring another variable s in your main function. line 7 of your code. and it's the variable which is used in cin. either delete that line or use :: before s.

long s;
cin >> ::s; //let it be 5
output();
like image 36
Roya Ghasemzadeh Avatar answered Oct 26 '25 15:10

Roya Ghasemzadeh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!