Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a meaning ascribed to where you put the pointer indicator "*" in Objective-C?

Tags:

objective-c

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?

like image 886
JohnRock Avatar asked Aug 29 '11 00:08

JohnRock


2 Answers

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.

like image 83
fluffy Avatar answered Sep 29 '22 10:09

fluffy


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.

like image 31
Graham Perks Avatar answered Sep 29 '22 10:09

Graham Perks