Home > Software engineering >  C Static variable inside function cannot be changes
C Static variable inside function cannot be changes

Time:01-31

Can someone please explain to me the following.

static_outer works as expected. When the print_str() function is called, static_outer is assigned the value from the parameter and then printed to output.

static_inner "misbehaves" a little. It is also assigned the value from the parameter, when the function is called. But when the function is called for the second time, the printed value is the same as in the first call.

Why doesn't the assignment change the value? My only intuition is that the line is ignored because the static_inner is already declared but compiler does not complain.

static const char* static_outer;

void print_str(const char* const str) {

    static const char* static_inner = str; 
    cout << static_inner << "\r\n";
    
    static_outer = str;
    cout << static_outer << "\r\n";
}

int main() {    
    const char str1[] = "Foo";
    const char str2[] = "Bar";

    cout << "First call" << "\r\n";
    print_str(str1);
    
    cout << "\r\n" << "Second call" << "\r\n";
    print_str(str2);
}

// Output:
// First call
// Foo
// Foo
//
// Second call
// Foo <--- this is the line in question... why not "Bar"?
// Bar

Live demo: https://onlinegdb.com/-OnqgsLTn

CodePudding user response:

Once a function static variable is initialized, the line static const char* static_inner = str; has no further effects.

If you want the variable to change every time it is called, you would need to have a line of code performing assignment:

void print_str(const char* const str) {

    static const char* static_inner;
    static_inner = str;
    cout << static_inner << "\r\n";
    
    static_outer = str;
    cout << static_outer << "\r\n";
}

CodePudding user response:

My only intuition is that the line is ignored because the static_inner is already declared

Your intuition is correct. That is exactly what happens. You are assigning the str parameter to static_inner in its declaration. A static local variable is initialized only one time, the first time the function is called. On subsequent calls, the variable retains its previous value.

To do what you want, you need to separate the static local variable's declaration from its assignment:

static const char* static_inner;
static_inner = str;
  • Related