*'s and white space



is the variable declaration:

NSString *myString

equivelent to:

NSString * myString

If so what are the conventions for *'s and whitespace (not in relation to arithmetic)? There are times when there is no space and others where there is. I realize this may be a silly question, but it is causing confusion for me.



Yes, they are equivalent. In C (and therefore ObjC), whitespace doesn’t mean anything and is completely stripped when the code is compiled. So, the whitespace between the star doesn’t matter to the compiler, but, there is a convention that for variable declarations, the star always goes on the variable name:

NSString *string;

and not on the type name:

NSString* string;

The reason is because the star is actually associated with the variable and not the type. For example,

NSString *string1, string2;

is incorrect as it is the same thing as:

NSString *string1;
NSString string2; // <-- Note the missing star there

Therefore, the proper way to declare two NSString * variables in one line is:

NSString *string1, *string2;

By keeping the star on the variable name, we don’t forget that fact. There shouldn’t be any cases of the star not being on the variable name in the book - if there are, let me know.


To be honest most of the confusion was from Kochan’s book, I have seen it in this book in the creation of autoreleaspools. Most of the time it is:

At other times (specifically in a chapter 2 code listing) I see:

I’m reading the book on my iPhone so I don’t know the exact page. I’m typing this from the iPhone as well so please forgive any typos.


I’ve seen this also. What was really getting me was when they put the * inside parentheses like:
(NSString *) stringOne;

Is this also the equivalent to NSString *stringOne; ?



You’ll only see variable types in parentheses for two reasons:

It’s an argument in a method, in which case, it must have parentheses:

- (void)method:(NSString *)arg;

Or if you are typecasting a variable.

NSString *a = (NSString *)someOtherVar;

You rarely need to typecast a variable.