ldog
ldog

Reputation: 12151

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 array a is 
//pointing too gone out
//of scope and garbage
//or is it still fine?
}

Upvotes: 4

Views: 186

Answers (3)

AnT stands with Russia
AnT stands with Russia

Reputation: 320719

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.

Upvotes: 3

Chris Dodd
Chris Dodd

Reputation: 126508

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.

Upvotes: 1

nos
nos

Reputation: 229304

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

Upvotes: 11

Related Questions