Reputation: 632
Suppose I have a simple console program as follows:
(haven't tested it and it may contain errors since I'm sort of a newbie)
#include <iostream>
using namespace std;
void startProgram();
int main(){
a = 20; //I want to somehow set this so that I can use it in any other function
//without passing it through like startProgram(a);
startProgram();
return 0;
}
void startProgram(){
cout << a << endl;
}
So... How do I make it so that I can change the value of 'a' or print it or do whatever without passing it through to every function?
And sorry if there are questions like this already, which I don't doubt, but I couldn't find any!
Thanks in advance!
Upvotes: 1
Views: 9844
Reputation: 179
You can make a global variable slightly better by putting it in a namespace, along with your functions. This way, only the functions that need to access this variable will have access.
In this example, startProgramA()
has access to a
. startProgramB()
does not.
namespace start_program_a
{
int a = 20;
void startProgramA()
{
cout << a << endl;
}
}
void startProgramB()
{
// This won't work!
// cout << a << endl;
}
Upvotes: 0
Reputation: 409442
There are really only two ways: Global variables or argument passing.
If you declare the variable as a global variable, i.e. in the global scope outside (and before) any functions then all function will be able to use it. However global variables should be used as little as possible. Instead I really recommend that you pass it as an argument, if other functions need to use the variable later, then continue to pass it on as an argument.
Or, of course, since you are using C++ why not define a class and make the variable a member of the class? Then you can put all related functions inside this class, and all can use the variable without making it global or passing it around as an argument.
Upvotes: 3