While you can resolve the issue of how to use a global, it is much better if you avoid it altogether. If you have two functions that modify a single variable, then the simplest thing you can do is to pass the variable as argument to the function:
void foo( type & var );
void bar( type & var );
int main() {
type t( constructor_argument ); // [1]
// [2] operate on t before calling the functions
foo( t );
// [3] operate some more if needed
bar( t );
// [4] t now has been updated by both foo and bar
}
If the variable does not need to be constructed before the first function ([1]
not required, and [2]
not present), then you can have that variable as a return value of the function:
type foo(); // create and return the variable
void bar( type& );
int main() {
type t = foo();
// [3] operate on t
bar( t );
// [4] use the final t
}
If you don't need to update the variable after calling the first function, and the second function does not actually modify the variable (it only reads what the first function did) and the variable is not needed in main
after the second function execution ([4]
is empty), then you can change the second function signature and avoid the variable in main
altogether:
type foo();
void bar( type );
int main() {
bar( foo() );
}
Any and all of the solutions to the different problems shown here are much better than having a global variable that is used by different functions. When you read the code in main
(or whatever the function that has the logic) it is obvious how the data is flowing from one point to another. In the case of globals, the need of calling foo
before calling bar
is not explicit in the code, the dependency on the global is hidden unless you read the implementations of the functions.
Avoid globals as much as possible, it will make your code more maintainable, easier to reason about and easier to test.