TExcelTAD
Home › Objective-C › C Foundations: Functions & Pointers

C Foundations: Functions & Pointers

Objective-C programs still use plain C functions (NSLog itself is one), and every object variable is a pointer. Understanding pointers is the key to reading Objective-C correctly.

C functions

A function has a return type, a name and typed parameters. It must be declared before it is used, so either define it above main or write a prototype first.

objc · try it yourself
#import <Foundation/Foundation.h>

// A prototype: tells the compiler the function exists
double celsiusToFahrenheit(double celsius);

// Functions can work with objects too
NSString *greeting(NSString *name, int hour) {
    if (hour < 12) {
        return [NSString stringWithFormat:@"Good morning, %@", name];
    }
    return [NSString stringWithFormat:@"Good afternoon, %@", name];
}

int main(void) {
    @autoreleasepool {
        NSLog(@"%.1f F", celsiusToFahrenheit(21.5));
        NSLog(@"%@", greeting(@"Mia", 9));
        NSLog(@"%@", greeting(@"Leo", 15));
    }
    return 0;
}

double celsiusToFahrenheit(double celsius) {
    return celsius * 9.0 / 5.0 + 32.0;
}
70.7 F
Good morning, Mia
Good afternoon, Leo

C passes arguments by value: the function receives a copy, so changing a parameter inside the function doesn't change the caller's variable.

Pointers

A pointer holds the address of a value. &x gives the address of x, and *p reads or writes the value the pointer points at.

objc · try it yourself
#import <Foundation/Foundation.h>

void doubleIt(int *number) {
    *number = *number * 2;   // write through the pointer
}

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main(void) {
    @autoreleasepool {
        int stock = 21;
        int *p = &stock;
        NSLog(@"stock = %d, *p = %d", stock, *p);

        *p = 30;
        NSLog(@"after *p = 30, stock = %d", stock);

        doubleIt(&stock);
        NSLog(@"after doubleIt, stock = %d", stock);

        int left = 1, right = 2;
        swap(&left, &right);
        NSLog(@"left = %d, right = %d", left, right);
    }
    return 0;
}
stock = 21, *p = 21
after *p = 30, stock = 30
after doubleIt, stock = 60
left = 2, right = 1

Passing a pointer lets a function change the caller's variable. Objective-C uses exactly this trick for errors: methods take an NSError ** (a pointer to an object pointer) so they can hand an error object back. You will meet it in the Errors lesson.

Objects are always pointers

In NSString *name, the * means name is a pointer to an NSString object that lives on the heap. You never put an object directly in a variable. Two pointer variables can therefore refer to the same object:

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSMutableString *draft = [NSMutableString stringWithString:@"Hello"];
        NSMutableString *sameDraft = draft;   // copies the pointer, not the object

        [sameDraft appendString:@", world"];

        NSLog(@"draft:     %@", draft);
        NSLog(@"sameDraft: %@", sameDraft);
        NSLog(@"same object? %@", draft == sameDraft ? @"YES" : @"NO");
    }
    return 0;
}
draft:     Hello, world
sameDraft: Hello, world
same object? YES

Changing the object through one variable is visible through the other, because there is only one object.

Concept C Objective-C
"no value" pointer NULL nil for objects (Nil for classes)
compare identity p == q a == b (same object?)
compare contents — [a isEqual:b], [s isEqualToString:t]

Note: == on objects compares addresses, not contents. Two different string objects with the same text are isEqual: but not ==. This is one of the most common beginner bugs.

Arrays of C values

C arrays are fixed-size blocks of values. They are useful for small, fast tables of numbers; for lists of objects you will use NSArray instead.

objc · try it yourself
#import <Foundation/Foundation.h>

double average(const double values[], int count) {
    double sum = 0;
    for (int i = 0; i < count; i++) {
        sum += values[i];
    }
    return count > 0 ? sum / count : 0;
}

int main(void) {
    @autoreleasepool {
        double temps[] = {18.5, 21.0, 19.5, 23.0};
        int n = sizeof(temps) / sizeof(temps[0]);
        NSLog(@"%d readings, average %.2f", n, average(temps, n));

        char word[] = "cocoa";       // a C string is an array of chars ending in '\0'
        word[0] = 'C';
        NSLog(@"%s has %zu letters", word, strlen(word));
    }
    return 0;
}
4 readings, average 20.50
Cocoa has 5 letters

When an array is passed to a function it "decays" to a pointer to its first element, so the function can't know the length: always pass the count along.

Test yourself

In NSString *title, what is title?

  1. The string object itself
  2. A pointer to an NSString object
  3. A C string
  4. A copy of a string

If int x = 4; int *p = &x; *p = 9;, what is x?

  1. 4
  2. 9
  3. the address of p
  4. undefined

What does a == b test for two object pointers?

  1. Equal contents
  2. Same object (same address)
  3. Same class
  4. Both non-nil