Trevor Hickey
Trevor Hickey

Reputation: 37884

Is accessing a static out of scope undefined behavior?

While speaking with a colleague of mine, they said that:

foo() {
    int *p;
    {
        int x = 5;
        p = &x;
    }
    int y = *p;
}

creates undefined behavior because lifetime rules and scope rules do not specify.

However:

foo() {
    int *p;
    {
        static int x = 5;
        p = &x;
    }
    int y = *p;
}

is not undefined! You end up with "indirect scoping" issues.

The use of terminology does not sound correct.
I know that static has nothing to do with scoping.
Is it true that the second case has defined behavior?

Upvotes: 20

Views: 1202

Answers (2)

mssirvi
mssirvi

Reputation: 147

quoting from here

The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.

so yes in the second case x is in existence during the complete life-time of the program.

hence has defined behavior.

Upvotes: 1

NathanOliver
NathanOliver

Reputation: 180935

Yes the second case has well defined behavior. A static variable is basically a global variable whose name is scoped to the scope it is declared in. It is initialized the first time the scope is entered and then it lives on for the life of the program.

So when we reach

int y = *p;

p points to a variable that you can no longer reach (can't get back to that code) but still has a valid lifetime.

To quote the standard [basic.stc.static]

All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program

emphasis mine

The first case is undefined as the lifetime of the local scope x ends at the } and trying to refer to it after its lifetime ends is undefined behavior.

Upvotes: 30

Related Questions