1. The C in Objective-C
Abstract
In this chapter, we will introduce the main concepts common to the Objective-C and C languages. Objective-C is based on the original C language. As a result of this special relationship, any program that is valid C code is also valid from Objective-C's perspective. This is why it is so important to be familiar with the basics of C, as well as how they relate to areas of object oriented programming, such as classes, messages, and interfaces.
In this chapter, we will introduce the main concepts common to the Objective-C and C languages. Objective-C is based on the original C language. As a result of this special relationship, any program that is valid C code is also valid from Objective-Cs perspective. This is why it is so important to be familiar with the basics of C, as well as how they relate to areas of object oriented programming, such as classes, messages, and interfaces.
Topics such as arrays, structures, pointers, variable declarations, variable types, and functions are part of the common vocabulary shared by these languages. Programmers who are fluent in such basic Objective-C techniques have a much better time at understanding and using object-oriented concepts.
To get you up to speed with the advanced abilities of Objective-C, we start the book with an overview of the most frequently used features inherited from the C language. In the next sections, you will see how to use such fundamental techniques to create simple programs that will be the building blocks of your future Objective-C applications.
Note
As you read the next few sections, please keep in mind the implicit assumption that every feature discussed here as being part of Objective-C is also available in plain C. This will be true throughout this chapter, unless explicitly stated.
Simple Statements
Programs in Objective-C are composed of syntactical elements that may be further categorized into functions, classes, and variable declarations. Functions contain statements, or variable declarations. Each statement in the language is ended by a semicolon or is enclosed in brackets (in the case of compound statements), which makes them easy to recognize by both human beings and compilers. Unlike languages that use indentation to define the possible end of declarations, Objective-C has an unambiguous way to mark their end using semicolons. For example, here are a few valid statements and variable declarations (their meaning will be explained in later sections):
int numberOfEmployees;
double totalPayment;
totalPayment = numberOfEmployees * 1000;
NSLog(@"test log");
if (1 > 2) totalPayment = totalPayment + 10;
Each of these lines is either defining an executable instruction or declaring an entity that will be later used by the program. We will examine in detail the syntax used in each of these cases, but for now it is important to recognize the nature of Objective-C statements and how they combine to create valid programs.
Variables
A variable is a location in memory where values can be saved and modified. Variables in Objective-C have to be of a particular type, which is explicitly defined when the variable is declared. Here are a few examples:
int anIntegerVariable;
float aFloatingNumber;
Note that the variable type is the first element in the declaration. The name of the variable follows, ended by semicolon, which marks the end-of-statement character. These two variable declarations create an integer and a floating number variable. Integer variables are required to contain only whole numbers, and the compiler will check that this is always the case. Even when a programmer forces a value of a different type into an integer variable, the content will still be converted to an integer number in all expressions where they appear.
More than one variable can be declared in a single statement. This is done by having additional variable names in the same statement, separated by commas. Here is another example showing multiple variables declared in the same expression:
int anIntegerVariable, aSecondIntegerVariable;
bool booleanVariable1, booleanVariable2;
There are a few rules that need to be observed when naming variables. The first rule is that variables can start only with alphabetic characters or the underscore character. The same is valid for additional characters in a variable name; however, numeric characters are also allowed, starting from the second position. Here are a few valid variable declarations:
int var1;
int _single_2_Position;
int long_variable_name;
In Objective-C, the underscore character is frequently used as a separator for long variable names. The goal is to increase readability for these long names without resorting to a mix of uppercase and lowercase letters. Some programmers, however, see no problem in mixing cases in the same variable. The following example, thus, is also very common:
int longVariableName.
Note
Variable naming is a style issue. Different programmers have different opinions on what looks better. However, we recommend that you be consistent in the use of variable naming styles. Dont use variables with mixed case in one place and variables separated by underscores in another. The basic idea is to avoid confusion and reduce the number of decisions you need to take each time you introduce a new name in a program.
Variable names, as well as all other identifiers in Objective-C, are case sensitive. This means that the following are two valid declarations for different variables:
int myVariable1;
int myvariable1;
The fact that case is significant in variable names makes the use of a unified naming style even more important. It would be very unfortunate to have a program failing because of the indiscriminate use of two variables that differ just by a single misspelled character.
Note
In the C language, names starting with single or double underscores followed by a capital letter are reserved. Only the compiler can use them, for the purposes of language implementation. Avoid the use of such names, since they may conflict with internal names used in future versions of the languageeven if they seem to work in your current compiler implementation.
Variable Initialization
A variable declaration can also be used to define the initial value of a variable. This is done using the assignment operator. Here is a simple example:
int daysInTheWeek = 7;
int monthsInTheYear = 12;
float PI = 3.14;
An initialization can also make use of arithmetic expressions or even function calls. Thus, it is possible to write code like this:
int secondsPerHour = 60 * 60;
Note
Variables should always be initialized to suitable values, since lack of proper initialization is one of the most common sources of programming errors. Variable initialization is combined with definition in Objective-C exactly to reduce the occurrence of such mistakes.
Variable Types
A variable needs to be declared of a particular type before it is used. There are several types that can be used in Objective-C. They can be generally classified as native or user-defined types.
A native type is predefined by the language and compiler implementation. These types are available without the use of any libraries or header files, so they can be used in any function or class defined in Objective-C. User defined types, on the other hand, are specified by programmers. They can either be part of libraries or of user code. I will first consider the available native types; structures and classes will be discussed later.