Significance of const keyword positioning in variable declarations
What is the significance of the positioning of the
c开发者_C百科onst
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!
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.
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.
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
精彩评论