Is it OK to reference an out-of-scope local variable within the same function?

后端 未结 4 907
野性不改
野性不改 2020-12-20 19:25

In this code, I reference the local variable b even though it is out of scope. But I do it from within the same function so it\'s probably still on the stack, r

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-20 19:47

    The problem here is not that b is out of scope. It is that the lifetime of b has ended. Scope is about where the name of an object is known. Lifetime is about when the object exists (within the computational model).

    Technically, the object b does not exist when you reference it with *a. The bytes that were used to represent it might happen to be still unchanged in memory, and accessing them with *a might happen to work sometimes, especially if optimization is not turned on, but it is undefined behavior.

    An object can still be accessible even though its name is not in scope. Here is an example of an object that is accessible during its lifetime even though it is not in scope:

    void foo(void)
    {
        int b;
        bar(&b);
    }
    

    In this code, the function bar may access b, even though it cannot see the name of b in foo. Although control leaves the block in which b is created, execution of the block is merely suspended, not terminated. So b continues to exist even while the function bar is executing. So b will be out of scope, but the access will be during its lifetime.

提交回复
热议问题