I was was reviewing a warning of some code that I wrote in the past and I noticed a warning around this code:
const int * aPointer = &x;
The integer located at
*pointer is constant. That means, trying to change the integer x through the pointer is not possible;
*aPointer = 20;
What to note here, is that you can still change the value of x by changing its value directly, this will also cause
*aPointer value to change.
However, trying to change the pointer using
aPointer = &y will execute successfully.
int * const aPointer = &x;
The pointer in this example is constant, but the value its pointing to can be changed using it.
*aPointer = 20; will change the value of x.
Whats constant in this example is the value of
aPointer; You cannot change what its pointing to after assigning it.
aPointer = &y
On the other hand, changing the value aPointer is pointing is allowed.
*aPointer = 123; // x now equals 123
In cocoa, constants pointers to strings are used extensively. One area of wide usage is to store the
UIKIT_EXTERN NSString * const UITextViewTextDidChangeNotification;
UITextViewTextDidChangeNotification above, is a constant pointer to a string. It points to a an instance of
NSString (in this case
The fact that
UITextViewTextDidChangeNotification is a const pointer and will always point to the same
NSString object and that
NSString is an immutable object. Makes sure that
UITextViewTextDidChangeNotification will always equal the string
I hope you enjoyed this refresher, for follow up, ping me on twitter @ifnottrue.