R – Confused on const correctness with static array of pointers to const objects

cconst-correctnessconstantsobjective cstatic

I'm still not sure I totally get how this particular case should work out. So if I want to declare an array of NSStrings that won't change, is this correct?

static NSString * const strings[] = {@"String 1", @"String 2", ...};

Is the static necessary? (what does it do?) Am I missing an extra const somewhere? There's just too many places for it to go! Gah! Am I doing it wrong, or am I just paranoid?

Best Answer

What you have:

static NSString * const strings[] = {@"String 1", @"String 2", ...};

Is an array of immutable pointers.

You might want:

static NSString const *strings[] = {@"String 1", @"String 2", ...};

An array of pointers to immutable NSString objects.

Or

static NSString const * const strings[] = {@"String 1", @"String 2", ...};

An array of immutable pointers to immutable NSString objects.

The "Clockwise-Spiral Rule" is the technique I use to interpret C declarations.

The static keyword means that the array's 'storage duration' is for the entire life of the program. If the declaration is in a function, then the array doesn't go away when the function returns (though the scope will still be only for that function). If the declaration is at file scope, the static keyword will make the name of the array visible only within that compilation unit (ie., source file). Another source file could not access the array through an extern declaration.