views:

170

answers:

3

What is the significance of the positioning of the

const

keyword when declaring a variable in Objective-C, for example:

extern const NSString * MY_CONSTANT;

versus

extern NSString * const MY_CONSTANT;

Using the first version in assignments produces warnings about "qualifiers from pointer target type" being discarded so I'm assuming that the second version ensures that the pointer address remains the same. I would really appreciate a more definitive answer though. Many thanks in advance!

+5  A: 

In the first case, you are declaring a mutable pointer to an immutable const NSString object, whereas in the second case, you are declaring an immutable pointer to a mutable NSString object.

An easy way to remember this is to look at where the * is situated; everything to the left of it is the "pointee" type, and everything to the right of it describes the properties of the pointer.

ezod
ezod is correct - However, I don't see the reasoning in adding the const, when an NSString is declared as a string constant. You can't release an NSString and you can't change it (its not mutable) ... so why even bother w/the const?
Mr-sk
No-one uses `const NSString *blah` because even an immutable NSString might need to manipulate its ivars (e.g., caching), and an NSString might also be an NSMutableString. You use `NSString *const blah` so that some of your other code doesn't do `if (MY_CONST_STRING = local_string)` and a malicious plugin can't rewrite all your constants to be `@"I LIKE MONKEYS"`.
Jeremy W. Sherman
+1  A: 

In general, const always applies to the token just before the const. In the second case, the const means that the pointer is a constant, not the thing pointed at. The exception is when the const appears before anything that can meaningfully be constant, as in your first example. In this case it applies to the first type, in this case NSString, so its equivalent to extern NSString const * MY_CONSTANT

Chris Dodd
I wish I could set two accepted answers, both have helped me understand this. Many thanks guys!
EddieCatflap
A: 

extern const NSString * MY_CONSTANT; - Pointer is variable , but the data pointed by pointer is constant.

extern NSString * const MY_CONSTANT; - Pointer constant , but the data pointed by pointer is not constant.

Jay