-1

I am tasked with trying to change the value of a static variable outside of a function in C.

I have viewed some posts on this topic, particularly some comments from this post: How to change local static variable value from outside function There is a comment that says to pass the variable through a reference/pointer parameter or to return by reference, but I feel as though I am lacking the understanding to implement this.

My understanding of a static variable is that memory for the variable is allocated only once, and is not released when the variable goes out of scope. According to What does "static" mean in C?, the static variable in a function retains its value between invocations, and is seen only in the file that it is declared in. I set up a basic example to show how static variables are traditionally used:

int myFunction();

    void main() {

    printf("%d ", myFunction());
    // console should show value of 1
    printf("%d ", myFunction());
    // console should show value of 2
    printf("%d ", myFunction());
    // console should show value of 3

    return 0;
}

int myFunction() {
    static int counter = 0;
    counter++;
    return counter;
}
omri
  • 352
  • 2
  • 18

1 Answers1

2

Make the function return the address of the variable.

int* myFunction() {
    static int counter = 0; 
    counter++; 
    return &counter; 
}

Then, in main you can use this function like:

int* ptr = myFunction();
*ptr = 0; // reset counter back to zero
Michael
  • 2,673
  • 1
  • 16
  • 27