Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 279
Ed Marty Avatar asked Feb 28 '23 03:02

Ed Marty


2 Answers

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.

like image 77
Michael Burr Avatar answered Apr 19 '23 23:04

Michael Burr


You read C declarations from the inside out, first moving right to highly bound operators like [] and then moving left. So, you have: strings, an array, of constant, pointers, to NSString, that is static.

That's perfectly reasonable but not what you said you wanted.

To create pointers to constant strings you will need the const on the other side of the *, so you will have strings, an array, of pointers, to constant, NSString, which are static.

You can put const in both places, if you want.

Using static storage class is a bit like defining a class variable. It is the same as static in C99, a module-level lexical scope.

like image 34
DigitalRoss Avatar answered Apr 19 '23 23:04

DigitalRoss