user3063491
user3063491

Reputation: 31

Create a new instance with same name through looping

As novice to Objective C, I cannot really understand why this is ok:

@autoreleasepool {
    for (int i = 0; i<10; i++) {
        NSNumber *newNumber = [[NSNumber alloc] initWithInt:(i)];
        NSLog(@"New number = %@", newNumber);
    }
}
return 0;

But not this:

@autoreleasepool {
    NSNumber *newNumber = [[NSNumber alloc] initWithInt:(0)];
    NSLog(@"New number = %@", newNumber);

    NSNumber *newNumber = [[NSNumber alloc] initWithInt:(1)];
    NSLog(@"New number = %@", newNumber);
}
return 0;

In both cases, I do redefine *newNumber (?) Why is it different?

Upvotes: 2

Views: 64

Answers (2)

HAS
HAS

Reputation: 19863

Variable names must be unique within a given scope.

A scope is defined by curly braces {}. Variables are only valid in the scope they are defined in (and in scopes within that scope).

If you have a loop like

for (int i = 0; i < 10; i++) {
    NSNumber *newNumber = [[NSNumber alloc] initWithInt:(i)];
    NSLog(@"New number = %@", newNumber);
}

newNumber is only available inside that for loop (between {}). After each iteration it is "gone".

If you have a scope like

@autoreleasepool {
    NSNumber *newNumber = [[NSNumber alloc] initWithInt:(0)];
    NSLog(@"New number = %@", newNumber);

    NSNumber *newNumber = [[NSNumber alloc] initWithInt:(1)];
    NSLog(@"New number = %@", newNumber);
}

both newNumber variables are within the same scope and therefore not unique.

Upvotes: 4

Greg Hewgill
Greg Hewgill

Reputation: 993303

Objective-C only allows you to declare the type of a local variable once within a scope. So the following is fine:

@autoreleasepool {
    NSNumber *newNumber = [[NSNumber alloc] initWithInt:(0)];
    NSLog(@"New number = %@", newNumber);

    newNumber = [[NSNumber alloc] initWithInt:(1)];
    NSLog(@"New number = %@", newNumber);
}

In this case, the second assignment to newNumber changes the value of the existing pointer, rather than creating a second pointer with the same name.

Upvotes: 1

Related Questions