Objective-C Lesson 2: Basic Variables

In almost all programs, values may change; these values are stored in variables, which, as the name implies, are designed to have varying contents as the program is used. We’ll dive right in with a sample program.

Program 2.1 // Introducing variables

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    int i;
    i = 1;
    NSLog (@"The variable i has a value of %d", i);

    i = 2;
    NSLog (@"The variable i now has a value of %d", i);

    [pool drain];
    return 0;
}

The output of this simple program is as follows:

The variable i has a value of 1
The variable i has a value of 2

Code, Demystified

Program 2.1 contains the same “boilerplate” code in the template that Xcode provides for you. It is still not necessary for now, so explanation will be deferred.

The first “real” line of the program introduces the concept of a variable.

int i;

This variable is declared to be of type int and with the name i. Before we talk about the variable type, we have to take about the choice of the variable’s name.

Variable Names

In C, all variable names (in fact, almost all names in general) must be made of lowercase and uppercase letters, digits, and the underscore character (_). The first character of the name must be a letter or underscore. Because Objective-C is a strict superset of C, the same rules apply.

Note that C and Objective-C are case-sensitive. A lowercase letter is not the same as a capital letter. Therefore, fraction, Fraction, FRACTION, and fractioN are considered four completely different names. As a result, programmers often use camel case to declare variable names of multiple words. Examples include aPairOfDice, lotsOfMoney, and someAddress.

Because of the wide variety of options available to you, make sure to choose descriptive variable names, such as taxRate instead of t. You can only thank yourself later on.

Reserved Names

The Objective-C language reserves certain words, so that you cannot use them as a name; in fact, some are reserved by C itself. For a complete list, check out this post.

Data Types

In program 2.1, the variable i was declared to be of type int. This means that i can only hold a whole-number value, without a decimal point—an integer. Integer values are one of four basic data types. The others are floating-point values, characters, and boolean values. Floating-point values are simply numbers that include a fractional portion, represented as a decimal, such as 5.2 and 10.0. Characters are any single character that you can type on your keyboard, such as A and @ and few others. Boolean values are either true or false; in Objective-C they represented as YES and NO.

Beyond the basics, C also defines three “adjectives” to modify the size of variables. These are short, long, and unsigned. An integer declared to be short will take up less memory than a standard int, and a long will take up more space. You can also use the specifier long long to indicate even larger values, but in OS X and iOS the additional long makes no difference. unsigned is used for values that will never be negative; this effectively doubles the maximum (positive) value of a variable without doubling its storage requirement (because every single negative value can now be “mapped” to a larger positive value).

short and long cannot be used in conjunction with each other in the same variable, but unsigned, or its optional counterpart signed, may be used on any variable, short, regular, or long.

Initialization

After declaring a variable, you have to initialize it with a value; otherwise, the variable would be useless. You can do this in a single statement, along with the declaration:

int variable = 1;

Alternatively, you can declare the variable, and then initialize it sometime later (it does not have to be the next statement):

int variable;
// Some code
variable = 1;

Printing Variables

Program 2.1 introduces a few new concepts in the NSLog statements.

NSLog (@"The variable i has a value of %d", i);

The real magic happens with the %d. This is a format specifier, and tells NSLog that it should expect a variable of a certain data type, and to print the value of that variable. In this case, the type %d tells NSLog to expect an integer value, and it does receive i as an argument, which is an integer value. Therefore, NSLog looks for the value of i, and prints the integer value. This explains the output:

The variable i has a value of 1

In the next few lines, we set i to the value 2, and then use NSLog to print it.

Note that the specifier %i is also used to print integer values.

Program 2.2 // Arithmetic operations with variables #import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    int result;
    result = 10 + 20;
    NSLog(@"The sum of 10 and 20 is %i", result);

    result = 25 - 30;
    NSLog(@"The difference between 25 and 30 is %i", result);

    result = 8 * 9;
    NSLog(@"The product of 8 and 9 is %i", result);

    NSLog(@"The quotient of 8 and 5 is %i", (8 / 5));
    NSLog(@"The quotient of 8.0 and 5.0 is %.1f", (8.0 / 5.0)); [pool drain];
    return 0;
}

The output is:

The sum of 10 and 20 is 30
The difference between 25 and 30 is -5
The product of 8 and 9 is 72
The quotient of 8 and 5 is 1
The quotient of 8.0 and 5.0 is 1.6

Program 2.2 presents some interesting situations. To begin, we define an integer value, and name it result. We set result equal to 10 + 20. Then we have the NSLog statement print out the value of the variable result, and we use the integer specifier because the result is an integer. The next few lines does the same, but note that negative values are supported. Multiplication works as expected, but the last two NSLogs deserve some attention.

The first thing to note is that you can specify an expression as an argument to NSLog, not simply a variable. As long as the result is of the proper type, NSLog doesn’t care whether you specify an expression or a variable.

Next, note that the first division results in a value of 1. Obviously, 8 ÷ 5 ≠ 1, but this is not a mathematical error. Remember that the format specifier %i is responsible for printing integers. Also note that the values 8 and 5 are both integers. This is an example of integer division. Through integer division, only the whole-number portion of the result is reported—any fractional portions are discarded.

To get the accurate result, we have to use floating-point numbers. These numbers are only syntactically different from ints in that they include a .0 portion at the end—as in 8.0 and 5.0. To print a floating-point value, we use the format specifier %f. The .1 portion of the specifier tells NSLog to only print the first decimal point, and disregard any others that may follow. Here, we can see that the result is indeed 1.6.

This post is part of the Learn Objective-C in 24 Days course.

0 comments


Or enter your name and Email
No comments have been posted yet.