Consider the following Objective-C code:
@interface ClassA : NSObject {
}
-(void) printVal;
@end
@implementation ClassA
-(void) printVal {
int val;
NSLog(@"%i", val);
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
ClassA* cA = [[ClassA alloc] init];
[cA printVal];
[cA printVal];
[cA printVal];
[pool drain];
return 0;
}
Why is this output:
2012-11-29 22:12:06.586 TestOne[20266:903] 0
2012-11-29 22:12:06.587 TestOne[20266:903] 32767
2012-11-29 22:12:06.588 TestOne[20266:903] 32767
In other words, why is val not reinitialized to 0 when it is redeclared, and why does it receive the value 32767 every subsequent time the method is called?
That is garbage value.
Initialise it with some value.
EDIT:
Storage class specifiers has some default value as
for auto- garbage value.
for static- 0.
for global/extern- 0;
for register-garbage.
In your case it is auto.
OHHH!!! I fotgot to answer your second part 🙁
Why initially it came as 0 and later on some 32767.
And you rightly pointed out in that link, now no need to explain in this answer. What can i do is refer to that link only.
How does an uninitiliazed variable get a garbage value?