开发者

C scope question

Is the following code valid

int main(){
int * a = 0;
if ( !a ) {
    int b[500];
    a = b;
}

//do something with a, 
//has the ar开发者_如何学Cray a is 
//pointing too gone out
//of scope and garbage
//or is it still fine?
}


No it is not, b has gone out of scope, accessing it (through the pointer) is undefined behavior.


As it often happens, the question you are asking is not really about scope, but rather about lifetime of an object. The lifetime of b array object ends at the end of the if block and any attempts to access it after that lead to undefined behavior.

In fact, pedantically speaking, it is even more about a than about b: once the lifetime of b ends, the value of a becomes indeterminate. An attempt to "do something" that relies on the indeterminate value of a pointer leads to undefined behavior.


Its undefined behavior -- the stroage duration of an obect declared in an inner scope (such as b here) lasts up until the end of the block in which its declared.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜