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; }
4 Respostas
+ 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
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?
0
You could declare "year" outside of any function definition. That should make it global (though I use the pointer way more often).
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.