-2

I'm looking for functionality similar to the python global keyword. I want to change a variable declared in main from a function.

For example:

void f() {
    x = 5;
}

int main() {
    int x = 0;
    f();
    cout << x; // prints 5

}

Any solution?

CSGregorian
  • 134
  • 1
  • 7

1 Answers1

9

Use a reference passed to the function

void f(int& x) {
    x = 5;
}

int main() {
    int x = 0;
    f(x);
    cout << x; // prints 5
}

or a global variable (discouraged!)

int x = 0;

void f() {
    x = 5;
}

int main() {
    x = 0;
    f();
    cout << x; // prints 5
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • How would I format this if I'm passing an array by reference? – CSGregorian Aug 25 '14 at 22:59
  • @CSGregorian What do you mean _"How would I format this if I'm passing an array by reference?"_? How to print a `std::array` or `std::vector` to `std::cout`?!? That's a completely different question, as what you've been asking for here! – πάντα ῥεῖ Aug 25 '14 at 23:02
  • No, no, sorry, forget the cout, that was just an example. If I wanted to pass an array, it would be `void f(int (&x)[])`, right? – CSGregorian Aug 25 '14 at 23:04
  • 1
    @CSGregorian You can't use references for c-style array types well, stick to `std::array` or `std::vector` to deal with reference parameters. Also you should clarify your question about this point. As it is, it has nothing to do with what you're actually asked in your comment here! – πάντα ῥεῖ Aug 25 '14 at 23:06