Here is an embarrassingly simple question that I have not been able to find an answer to as I delve into Objective C:
Is there a meaning ascribed to where you put the pointer indicator '*' when declaring or assiging a variable?
I have seen variables defined in different ways:
NSString *BLANK_SPACE = @" ";
NSString const *BLANK_SPACE = @" ";
NSString * const BLANK_SPACE = @" ";
Now I know the meaning of the CONST modifier, but I put it there only because when I see the asterisk separated by a space, it is usually before a CONST modifier.
Can someone explain the rationale about where to put the * when declaring/assigning a variable? What is the difference?
const
is a postfix operator that refers to the thing to its left, as opposed to the right. If the const
comes first then it applies to the first thing after it. const NSString *foo
(as well as NSString const *foo
) means that it's a non-const pointer to a const NSString - the pointer value can be reassigned, but the data being pointed to is immutable. NSString * const foo
means that it's a const pointer to a non-const NSString - the data being pointed to can change but the location the pointer refers to cannot.
Spacing between the *
and other parts of the line are just a matter of style and clarity.
The trick is to read the declarations from right to left. So:
NSString *BLANK_SPACE
Right to left... BLANK_SPACE is a pointer to an NSString.
NSString const *BLANK_SPACE
Right to left... BLANK_SPACE is a pointer to a const NSString.
NSString * const BLANK_SPACE
Right to left... BLANK_SPACE is a const pointer to an NSString.
Finally,
NSString const * const BLANK_SPACE
Right to left... BLANK_SPACE is a const pointer to a const NSString.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With