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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With