0

HOW TO use variable from all functions?

For a little game I want to declare an int variable that is accessable and overwritable from any of my functions. How do I have to change the following minimal example for it to work and why? ===== code ==== #include <iostream> using namespace std; void test() { if(year<1900) { cout << "Oldfashioned!" << endl ; } else { cout << "That was a mistake." << endl ; } }; int main() { int year = 1880; // shall be accessable from every function test(); return 0; }

18th Jan 2018, 11:32 AM
LĂ©on Geide
LĂ©on Geide - avatar
4 Answers
+ 1
You could make a pass a pointer (or a memory address), like this: (You can even edit the variable within the function.) https://code.sololearn.com/cSxHTrOxEiD1/?ref=app
18th Jan 2018, 11:54 AM
blackcat1111
blackcat1111 - avatar
0
Hello blackcat, thanks for your suggestion. I use a pointer as the argument of a function sometimes, but I don't want to pass this variable on every occasion I use it. Do you / does someone have a more general idea?
18th Jan 2018, 12:04 PM
LĂ©on Geide
LĂ©on Geide - avatar
0
You could declare "year" outside of any function definition. That should make it global (though I use the pointer way more often).
18th Jan 2018, 12:09 PM
blackcat1111
blackcat1111 - avatar
0
Thanks for that suggestion; I tried it and guess it worked. I now put all commands in a new class "game" where I defined the variable. This should make it accessable better. I'll try it and see how it works.
18th Jan 2018, 8:44 PM
LĂ©on Geide
LĂ©on Geide - avatar