I have a function that uses a static variable to count how many times it got called:
void func ()
{
static int counter=0;
counter++;
/* some code */
}
The code in the function executes differently depending on the counter.
As it happens while expanding the program to have more features etc. the original implementation is insufficient and there are cases where counter
needs to be modified to get the correct behavior.
This however turns out to be quite a challenge as the function in question is already in use all over the program, which means that changing things like the function parameters would break a lot of prexisitng code.
After thinking about this problem I came up with the following two solutions:
Solution 1:
int& func ()
{
static int counter=0;
counter++;
/* some code */
return counter//return an lvalue reference
}
int main()
{
/* some code */
func()=2;//modify anonymous variable of type lvlaue reference, referencing counter
/* some code */
return 0;
}
Solution 2:
int* func ()
{
static int counter=0;
counter++;
/* some code */
return &counter//return a pointer
}
int main()
{
/* some code */
*func()=2;//modify anonymous variable of type pointer, pointing to counter
/* some code */
return 0;
}
As far as I can tell it works, but to me it looks rather suspicious, especially since I haven't ever seen such practices.
I understand the code as follows in the first solution it returns counter
by reference, so after func
evaluates to an anonymous object in the expression in main()
, which happens to be an lvalue reference to counter
. That effectively lets main()
modify a variable that's out of scope.
The second solution works analogously, but using a pointer instead of an lvalue reference.
And since in both cases counter
, as a static variable, has a lifetime that ends with the program the variable/memory address returned stays valid, even though it is accessed out of scope.
But is my interpretation correct? Is it undefined behavior after all and I just got lucky that it worked?
And if it is correct would it be considered bad code design given the circumstances?