A free book for starting with Cocoa using Objective-C

Page 9

Become An Xcoder

From the big issue a compiler makes out of forgetting a semi-colon, you will understand that programming is all about details. One of those details to pay attention to is the fact that code is case-sensitive. That is, it matters whether you use capitals or not. The variable name pictureWidth is not the same as pictureWIDTH, or PictureWidth. In accordance with general conventions, I make my variable names up by fusing several words, the first without capital, and all other words making up the variable name starting with a capital, just as you can see in example [2]. This style is often called camelCase. By sticking to this scheme, I reduce the chance of programming mistakes due to case-sensitivity tremendously. Please note that a variable name always consists of a single word (or single character, at a pinch). While you have plenty freedom choosing variable names, there are several rules which a variable name has to conform with. While I could spell them all out, that would be boring at this point. The prime rule you must obey is that your variable name may not be a reserved word of Objective-C (i.e., a word that have a special meaning to Objective-C). By composing a variable name as contracted words, like pictureWidth, you are always safe. To keep the variable name readable, the use of capitals within the variable name is recommended. If you stick to this scheme, you'll have fewer bugs in your programs. If you insist on learning a couple of rules, finish this paragraph. Apart from letters, the use of digits is allowed, but a variable name is not allowed to start with a digit. Also allowed is the underscore character: "_". Here are a few examples of variable names. Good variable names: door8k do8or do_or Not allowed: door 8 (contains a space) 8door (starts with digit) Not recommended: Door8 (starts with capital)

Using variables in calculation Now we know how to give a variable a value, we can perform calculations. Let's take a look at the code for the calculation of the surface area of a picture. Here is the code [3] that does just that. //[3] pictureWidth=8; pictureHeight=6; pictureSurfaceArea=pictureWidth*pictureHeight;

Surprisingly, the compiler doesn't nitpick about spaces (except within variable names, keywords etc.!). To make the code easier on the eyes, we can use spaces. //[4] pictureWidth = 8; pictureHeight = 6; pictureSurfaceArea = pictureWidth * pictureHeight;

01:2

A program is a series of instructions


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.