Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 38 ยท Control Flow and Functions

Functions

Learn how to write C functions in Objective-C, pass values and pointers, return structs, use static inline helpers, and decide between a function and a method.

Objective-C methods live inside classes, but the language also keeps all of C's plain functions. Cocoa uses them heavily: NSLog, NSMakeRange, NSStringFromClass, CGRectMake, dispatch_async. Functions are the right tool for small, stateless helpers that do not belong to any object. This lesson shows how to define and call them, how arguments are passed, and when a function is a better choice than a method.

Defining and calling a function

A function has a return type, a name, parameters and a body:

OBJECTIVEC
static NSInteger square(NSInteger n) {
    return n * n;
}

NSInteger result = square(7);    // 49

A function must be declared before use, either by defining it earlier in the file or with a prototype:

OBJECTIVEC
NSInteger square(NSInteger n);   // prototype, usually in a header

void as a return type means nothing is returned. Write (void) for an empty parameter list in C: int rollDie(void). An empty () means "unspecified arguments" in older C, and clang warns about it.

Pass by value

Arguments are copies. Changing a parameter never changes the caller's variable:

OBJECTIVEC
void tryToChange(int x) { x = 100; }

int a = 5;
tryToChange(a);   // a is still 5

Objects are passed as pointers, so the function receives a copy of the address. It can message the same object and mutate it if it is mutable, but reassigning the parameter does not affect the caller:

OBJECTIVEC
void appendBang(NSMutableString *s) { [s appendString:@"!"]; }   // visible to the caller
void replace(NSMutableString *s)    { s = [NSMutableString stringWithString:@"new"]; }  // not visible

To give the caller a changed pointer or primitive, pass the address of the variable (an out-parameter), as with NSError **.

Returning several values

C functions return one value, so you have three options: return a struct, use out-parameters, or return an object such as an array or dictionary.

OBJECTIVEC
typedef struct { double min; double max; } ABCRange;

ABCRange rangeOf(const double *values, size_t count) {
    ABCRange r = { values[0], values[0] };
    for (size_t i = 1; i < count; i++) {
        if (values[i] < r.min) { r.min = values[i]; }
        if (values[i] > r.max) { r.max = values[i]; }
    }
    return r;
}

Small structs are efficient to return by value. This is how NSMakeRange and CGRectMake work.

static and inline

A function declared static is visible only in its own .m file, which avoids name clashes in a language without namespaces. Cocoa-style code uses it for private helpers:

OBJECTIVEC
static BOOL isValidEmail(NSString *text) {
    return [text containsString:@"@"];
}

A header can define a tiny helper with static inline so each file that includes it gets its own copy, and the compiler may expand it in place:

OBJECTIVEC
static inline CGFloat ABCClamp(CGFloat v, CGFloat lo, CGFloat hi) {
    return v < lo ? lo : (v > hi ? hi : v);
}

Global (non-static) functions need a unique, prefixed name such as ABCClamp, and a prototype in the header.

Function or method?

Use a function when Use a method when
It needs no object state It reads or changes an object's data
It is a pure calculation or a conversion It should be overridden by subclasses
Speed in tight loops matters It is part of a class's public behaviour
It wraps a C API You want dynamic dispatch, protocols, KVC

Methods go through message dispatch, which costs a little more than a direct function call and can be intercepted at run time, which is a feature. Functions cannot be overridden or swizzled easily.

Documentation and parameter checks

Describe a function with a comment in a header, and validate arguments that can be wrong. For programmer errors, use NSParameterAssert, which raises an exception in debug builds:

OBJECTIVEC
NSString *ABCInitials(NSString *fullName) {
    NSParameterAssert(fullName != nil);
    // ...
}

Stand-in: pass by value, pointers and struct returns

C Stand-in (C): by-value copy, out-parameter and returned struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: static helpers and inline clamp

C Stand-in (C): static inline helper and a prefixed API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The last helper takes a function as a parameter; that idea has its own lesson, Function Pointers and Recursion.

Common mistakes

  • Calling a function before it is declared.
  • Returning a pointer to a local variable.
  • Expecting parameters to change the caller's variables.
  • Leaving a non-static helper unprefixed, which clashes with another library at link time.
  • Forgetting the (void) in a no-argument prototype.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a function receive when you pass an NSMutableString *?

    The pointer is copied by value, but both copies address the same object.
  2. 2. How can a C function return two values?

    Return a struct, use pointer parameters or return an object holding both values.
  3. 3. What does static mean on a function?

    Static gives internal linkage: the name is private to the translation unit.
  4. 4. Which is the better choice for a helper that clamps a number?

    A pure calculation with no object state fits a small inline function.

Summary

  • C functions are fully available in Objective-C and are used for stateless helpers and C APIs.
  • Arguments are passed by value; use pointers for out-parameters.
  • Return several values with a struct, out-parameters or a collection object.
  • Use static for file-private helpers and static inline for tiny header helpers.
  • Choose a method when the behaviour depends on an object or must be overridable.

Next: Function Pointers and Recursion