Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between NSString* mystring and NSString *mystring

Tags:

objective-c

I've come across several examples which declares classes in the header differently like

NSString* mystring;

or

NSString *mystring;

What's the difference?

like image 499
b1ade Avatar asked Mar 08 '11 10:03

b1ade


3 Answers

Those are three totally distinct lexical elements and the amount of whitespace in-between them is totally irrelevant. These are all equivalent in terms of what the compiler generates:

NSString*x;
NSString *x;
NSString* x;
NSString * x;
NSString                 *                 x;
NSString /* comment here */ * /* and another */ x;

I prefer the NSString *x variation since the pointer specifier belongs to the variable, not the type. By that, I mean that both of these:

int *x, y;
int* x, y;

create an integer pointer called x and an integer called y, not two integer pointers.

like image 189
paxdiablo Avatar answered Nov 16 '22 05:11

paxdiablo


There is no difference. It's a matter of style.

In Objective-C, you can pretty much think of the star as part of the 'type' of the variable.

However, the compiler interprets the star as "treat this variable as a pointer to the declared type" (in this case NSString). Where it gets interesting is defining multiple variables at once:

NSString *myString, *yourString;

You must use the star on each variable.

like image 26
bvanderveen Avatar answered Nov 16 '22 05:11

bvanderveen


Is preference, and is useful if you declare multiple variables in the same line, viz

NSString* mystring1, mystring2;  // Misleading, mystring2 is not a *

NSString *mystring1, mystring2;  // Is more clear 
like image 45
StuartLC Avatar answered Nov 16 '22 06:11

StuartLC