Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable scope with same variable name?

Tags:

objective-c

(Objective C Code)

int i=5;
{
    int i=i;
    NSLog(@"Inside Scope: %i",i);
}
NSLog(@"Outside Scope: %i",i);

Prints:

3385904 (Garbage)

5


replacing int i = i; with int i= 10; prints correctly... (Inside the scope's i)

Such as:

10

5

And (This code alone)

int i=i;

Compiles, but segfaults immediately.


How are any of these syntax's valid? What use are they, or are they compiler bugs that should have been caught earlier?

Is there any situation where it is necessary for using the same variable names inside a new scope under a new type, and how would you differentiate?

My only thoughts is could be the for() loop, as the compiler would be upset you're redefining int i; twice if you have two loops.

like image 353
Ryan Copley Avatar asked Mar 01 '26 11:03

Ryan Copley


1 Answers

Because you're redefining i, you're setting i to the value for itself that hasn't been set yet.

Simply turning this:

int i=5;
{
    int i=i;
}

into this:

int i = i;
//int i=5;
//{
    //int i=i;
//}

will give you the same varied results. This problem has nothing to do with scope.

like image 59
Matisse VerDuyn Avatar answered Mar 07 '26 11:03

Matisse VerDuyn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!