When I create an instance of a class called, say, Sprite, I do something like:
Sprite *mySprite = [[Sprite alloc]init];
But why when creating a CGSize or int type variable, I can't use *? Basically, what's the * for?
C++ will allow you to declare a variable anywhere in the program as long as the variable is declared before you use it. A good programming practice to develop is to declare variables at the top of a function.
Modern C compilers such as gcc and clang support the C99 and C11 standards, which allow you to declare a variable anywhere a statement could go. The variable's scope starts from the point of the declaration to the end of the block (next closing brace). You can also declare variables inside for loop initializers.
A declaration of a variable is where a program says that it needs a variable. For our small programs, place declaration statements between the two braces of the main method. The declaration gives a name and a data type for the variable. It may also ask that a particular value be placed in the variable.
The recommended practice is to put the declaration as close as possible to the first place where the variable is used. This also minimizes the scope. From Steve McConnell's "Code Complete" book: Ideally, declare and define each variable close to where it's first used.
The * denotes a pointer. CGSize
is declared as a struct
and Sprite
is a class, and in Objective-C all classes are referenced by a pointer.
You can find additional information in the Programming with Objective-C documentation. The relevant sections are Use Pointers to Keep Track of Objects and Methods Can Return Values.
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