1

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!

3
  • 1
    Make it global. But why don't you want to pass it? That's the much better way in most cases. Commented May 12, 2013 at 3:55
  • 1
    Because then I'd have to be passing and returning tons of variables, since I'm going to try to use it in a bigger scale than the example above.. Commented May 12, 2013 at 4:00
  • 3
    Welcome to programming. If you get too many variables put the related ones into a struct or similar. The bigger your scale the more likely you will screw up by stepping on your globals and having side effects. Commented May 12, 2013 at 4:02

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.