Reputation: 873
(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.
Upvotes: 3
Views: 155
Reputation: 1138
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.
Upvotes: 1