Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variables and MPI

I know that global variables are bad and should be avoided as far as possible. However, when writing parallel programs with MPI for example, some variables only get initialised once, and never changed (This task's number, total number of tasks etc.). Is it still considered bad practice to have these variables as global? Since you pretty much need access to these variables all the time, it seems silly to make a class for them in main, and pass a pointer to it to 99% of all the functions in the program. My approach so far has been to hide them in a namespace mpi_glob (for the case of C++, I guess I would not bother to put them in a struct in C to emulate a namespace). I guess the question also goes for other set-only-once variables such as a system of units etc.

like image 475
user787267 Avatar asked Aug 14 '12 11:08

user787267


1 Answers

The reason that global variables "are bad" is that they introduce coupling between separate source files that can be hard to identify and trace. In particular, if a global variable has an unexpected state at some point in the program, it can be hard to figure out where it got modified.

Replacing global variables with local variables that get passed by reference to every function in the program doesn't eliminate that problem. In design terms, it's "tramp data", i.e., data that wanders around even where it's not needed.

Now, the point here is that, as you suggest, data that's initialized once and never changed doesn't have the problems that make global variables "bad". Since the problem doesn't exist, the solution isn't needed.

like image 154
Pete Becker Avatar answered Sep 22 '22 16:09

Pete Becker