mozharovsky
mozharovsky

Reputation: 1265

iOS int type default value issue

I have an interesting issue with an int variable in my code that simply declares the variable each time it's being invoked and increase by 1. As well as I understand the point, when we call a method the computer puts the frame with this call and its local variables in a stack (that is accessible and suitable to access). But there is something wrong going on in practice. I get an integer of 32754 increased by 1 (i.e. 32755).

It's far away from int's maximal value, but in any way it doesn't work as I supposed it did. Somehow the second time variable isn't initialized properly (it should be var = 0). So I wonder how it works and what lies under the hood.

My "wrong" code:

- (IBAction)pressed:(id)sender
{
    int num;
    NSLog(@"Num is %d", num);
    num++;
    NSLog(@"Num is %d", num);
}

Working code:

- (IBAction)pressed:(id)sender
{
    int num = 0;
    NSLog(@"Num is %d", num);
    num++;
    NSLog(@"Num is %d", num);
}

Upvotes: 0

Views: 79

Answers (2)

Andrea Mario Lufino
Andrea Mario Lufino

Reputation: 7921

Local variables that aren't static are not initialized to any defined value, so you have to init that variable

Upvotes: 1

Peter Pei Guo
Peter Pei Guo

Reputation: 7870

Non-static local variables are not initialized, and that's what happened in this case.

Static variables, global variables and instance variables are initialized to 0.

Upvotes: 0

Related Questions