I'm developing a project that takes several command-line arguments, and uses these as parameters for subsequent simulations. (I want to run a large number of experiments in a batch).
What's the best way to set global variables at runtime? Global in terms of: the variables may change in the duration of a run, but should be accessible across a large number of classes.
Currently I read them into a Config object which I include in other classes. If anyone has better ideas (xml?) I'm all ears.
Thanks!
Master C and Embedded C Programming- Learn as you go Non-const global variables are evil because their value can be changed by any function. Using global variables reduces the modularity and flexibility of the program. It is suggested not to use global variables in the program.
You can access the global variables from anywhere in the program. However, you can only access the local variables from the function. Additionally, if you need to change a global variable from a function, you need to declare that the variable is global. You can do this using the "global" keyword.
It is seldom advisable to use Global variables as they are liable to cause bugs, waste memory and can be hard to follow when tracing code. If you declare a global variable it will continue to use memory whilst a program is running even if you no longer need/use it.
Use Local Variables Instead The idea is that the global variable gState is replaced by the local variable sState in the script of your main application stack. All references to the variable in the application can be replaced with calls to either setState or getState.
Bring all the related variables under one roof for ease of access. 2 approaches are possible:
namespace Configuration {
extern int i;
extern bool b;
extern std::string s;
}
class Configuration { // provide proper access specifier
static int i;
static bool b;
static std::string s;
}
To track them nicely, use getter()-setter() methods as wrapper inside namespace/class.
With getters-setters you can handle them in a thread-safe way, if the program demands.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With