I have a program that uses an external API which uses its own state. The program stores the initial state at the beginning. Afterwards, dozens of functions are invoked using a dispatcher depending on the input. Each of them alters the current state using the API. One of the functions should be able to reset the current state to the initial. Although, that would require access to the variable/constant set at the beginning, which is out of scope in the function.
One solution would be a global, which is considered evil. Another solution could be a function with a static variable to store the initial state at its first call. Calling it again would return the static state. Although, this is not really an improvement.
Is there any clean, maintainable solution to this problem?
Edit: OK, let’s say I’ll use a const global after all. To illustrate it, I’ll use the following code:
extern int get_state();
extern void set_state(int);
const int initial_state = get_state();
int main()
{
while(1) {
// call dispatcher, eventually
break;
}
set_state(initial_state);
return 0;
}
The problem is that the initializer of initial_state must be constant, which get_state() apparently isn’t. Is there any way to work around this?
Globals aren’t evil (especially if constant).
Any other solution would likely be ugly and would have a better chance of introducing bugs.