3

(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.

2
  • 1
    I'm not sure what the spec says about int i = i;, but clearly it's invalid. Defining a new i inside {} is perfectly legit, however, and occasionally useful (though potentially confusing and bug-prone). Commented Feb 13, 2012 at 17:24
  • 1
    I wish that you could set (or really that it was default) to have the compiler throw up an error when you use the same variable name in two scopes in the same method. I never want to do that. Perhaps there is such a flag... oops guess that's a question. Commented Feb 13, 2012 at 17:46

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The second one segfaults, the first one does not. They are not exactly the same situation...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.