I am getting this error
error: Access.Core may be used uninitialized in this function
And this is my code:
static int FirstTime = 1; MyStruct Access; if (FirstTime) { FirstTime = 0; Access = Implementation(); DoSomething(Access); } if(Other_Variable) { Access = Implementation2(); DoSomething(Access); } //The Other_Variable will be set to 1 and to 0 by other part of the code
My code is like that because I want to call to the function Implementation only the first time. In every call the Access variable is going to be updated so it does not make many sense make it static.
If I make Access static works, but I do not like make it static because in every other call Access is going to be updated. Any way to avoid the problem without making it static?.
Also any better options to execute only once a function instead of using a static variable are welcome.
Make
Accesslike this (and removeFirstTimeand theif):The reason you get this warning is because static variables survive one function call. Their value is retained across all function calls (without regard to which thread calls that function). So,
FirstTimewill control whether you initializeAccess. The first time you call the function that code is in will correctly initialize theAccessvariable. But with every further function call,FirstTimeis zero, and you will not initializeAccessanymore, and thus will use an uninitialized variable down the code.Edit: Now, with your updated information, you say that you have two
Implementationfunctions. The first time you want to use one, and all the other times you want to use another function. How about this then:Depending on your actual use case, there may be better ways to handle this, though. For example, why not update the state of
Access, like this:Something like this for
MyUpdater:That pattern is called
RAII: You associate some useful action with the constructor and destructor of a locally allocated object.