I am just learning objective-C, and am wondering why the following code results in an error?
Person *p = [[Person alloc] init];
Person *p = [[Person alloc] init];
In this case, the second line gives an error stating the "p" pointer has already been defined.
This makes sense to me; however, if it is true that a pointer cannot be re-defined, then why does the following code work?
for(int i = 0; i<10; i+=1) {
Person *p = [[Person alloc] init];
}
When I enter this in XCode it does not give any errors, and it compiles and runs just fine. In this case, I'd expect the loop to simply re-define the "p" pointer, similar to having them be declared sequentially, but this is not the case.
Does anyone have an explanation for why this is?
Person *p = [[Person alloc] init];
Person *p = [[Person alloc] init];
In the first case, two p
in the same local scope, they are all local variables, so they have the same priority. We can't have two variable with the same name and the same priority.
Person *p = [[Person alloc] init];
{
Person *p = [[Person alloc] init];
}
The above case will be ok because the second p
has higher priority in its local scope than the first p
.
for(int i = 0; i<10; i+=1) {
Person *p = [[Person alloc] init];
}
In the second case, all the p
are in different local scopes.
In a nutshell, it is because in the case of the for-loop the variable p
is local to the loop itself, so at the end of each iteration p
and any other variables local only to the loop's scope is deallocated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With