c++staticconstantsvariable-assignmentredeclaration

C++ Static variable inside function cannot be changes


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


Solution

  • 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. That is the whole point of declaring a local variable as static.

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

    static const char* static_inner;
    static_inner = str;