3

I created an enum like this

typedef NS_ENUM(NSInteger, PermissionStages) {
    thePermissionNotDetermine = 0,
    thePermissionDenied = 1,
    theReminderPermissionAllowed = 2,
};

And create a variable like this

PermissionStages PermissionStageVar;

I have not assign any value to it, but by default this variable has PermissionStages enum first value, in this case its thePermissionNotDetermine

Why is this behavior?

S.J
  • 3,063
  • 3
  • 33
  • 66
  • This is the default behaviour of enums. You know in computer science 0 is a meaningful value in contrast to real world. You better assign a value of -1 to the undermined case. – Adeel Miraj Nov 17 '16 at 15:55
  • The initial value could be different depending on where you are creating that variable. Local variables aren't automatically defaulted to 0. – dan Nov 17 '16 at 15:59

1 Answers1

5

The line:

PermissionStages PermissionStageVar;

is getting a default value of 0. This is similar to the line:

NSString *foo;

resulting in foo having an initial value of nil. Or

BOOL aBool;

resulting in aBool having an initial value of NO.

The variables are all initialized to a value of "0".

Since your enum happens to have a value with 0, your variable appears to be initialized with thePermissionNotDetermine.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 1
    is there any way to initialize PermissionStageVar with some other default value other then these, and which I don't use in code accept assigning as default value? – S.J Nov 17 '16 at 16:09
  • 1
    `PermissionStages PermissionStageVar = (PermissionStages)-1;` would be a way to force it to some other value. I don't recommend it though. The enum should only reference actual valid values. – rmaddy Nov 17 '16 at 16:15
  • 1
    local variables are not initialized to 0, with the exception of objective-c object references. So if your local BOOL has an initial value of NO, that is just a happy accident. See https://stackoverflow.com/questions/10022025/local-variables-set-to-nil-objective-c – polytopia Jan 19 '18 at 16:11