I'm trying to a NSString constant in my .h file to be defined in my .m. I understand that
extern NSString * const variableName;
in the .h and
NSString * const variableName = @"variableValue";
is the way to do this. Examining c tutorials I see that const
is supposed to go before variable definitions. My question is why is it not declared as extern const NSString * variableName;
in the .h and const NSString * variableName = @"variableValue";
in the .m. I know this doesn't work because I encounter compiler warnings which say 'Passing argument 1 of methodName: discards qualifiers from pointer target type'. What does this mean?
2 Answers
It's not the same. The const modifier can be applied to the value, or the pointer to the value.
int * const
A constant pointer (not modifiable) to an integer (its value can be modified)
const int *
A modifiable pointer to a constant integer (its value can't be modified)
So you can imagine:
const int * const;
-
29To expand on that, if you're not dealing with a pointer,
const int
andint const
are exactly the same.NSString
s are already immutable, so the const only needs to be applied to the pointer (which can be a little confusing since Objective-C objects are always accessed via pointers).– WevahJul 7, 2010 at 16:34 -
1@Macmade why didn't you explain this in terms of NSString since the syntax is different anyways with the pointer?– jpswainOct 18, 2012 at 16:57
-
1To expand on that,
const int *
andint const *
are the same, butint * const
is different. Nov 13, 2012 at 2:10 -
2@Wevah: "NSStrings are already immutable" but an NSString pointer can still point to an NSMutableString Nov 13, 2012 at 2:11
Constant pointer is NOT a pointer to constant. Constant pointer means the pointer is constant. E.g. constant pointer int * const ptr2;
indicates that ptr2
is a pointer which is constant. This means that ptr2
cannot be made to point to another integer. However, the integer pointed by ptr2
can be changed.
Whereas a pointer to constant const int * ptr1;
indicates that ptr1
is a pointer that points to a constant integer. The integer is constant and cannot be changed. However, the pointer ptr1
can be made to point to some other integer.