Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 38 ยท Control Flow and Functions

Variadic Functions and Storage Classes

Learn how to write variadic functions and methods with va_list, nil-terminated argument lists, and how static, extern, auto and register control scope and lifetime.

Two topics finish the control-flow chapter: functions that accept a variable number of arguments, such as NSLog and +[NSArray arrayWithObjects:], and the rules for where variables live and how long they last. Both come straight from C, and Cocoa code uses both every day.

Variadic functions

A function with ... as its last parameter accepts any number of extra arguments. printf and NSLog are variadic. You write your own with the macros from <stdarg.h>:

OBJECTIVEC
#include <stdarg.h>

NSInteger ABCSum(NSInteger count, ...) {
    va_list args;
    va_start(args, count);
    NSInteger total = 0;
    for (NSInteger i = 0; i < count; i++) {
        total += va_arg(args, NSInteger);
    }
    va_end(args);
    return total;
}

NSInteger s = ABCSum(3, (NSInteger)10, (NSInteger)20, (NSInteger)30);   // 60
  • va_start(args, last) begins reading after the last named parameter.
  • va_arg(args, type) returns the next argument as type.
  • va_end(args) cleans up.

The function has no way to know how many arguments there are or what their types are, so the caller must communicate that: by a count (as above), by a format string (printf), or by a terminator.

Nil-terminated lists in methods

Cocoa's variadic methods use a nil terminator. A method declares , ... after its last argument:

OBJECTIVEC
+ (NSArray *)listWithItems:(id)first, ... NS_REQUIRES_NIL_TERMINATION;

+ (NSArray *)listWithItems:(id)first, ... {
    NSMutableArray *result = [NSMutableArray array];
    va_list args;
    va_start(args, first);
    for (id item = first; item != nil; item = va_arg(args, id)) {
        [result addObject:item];
    }
    va_end(args);
    return result;
}

NSArray *a = [ABCList listWithItems:@"x", @"y", @"z", nil];

Forgetting the final nil reads garbage from the stack, which is a classic crash. NS_REQUIRES_NIL_TERMINATION makes the compiler warn about it. That is also why array literals (@[ ... ]) are preferred: no terminator to forget.

Forwarding to formatted output

To wrap a format-string API, pass the va_list to the "v" variant:

OBJECTIVEC
void ABCLog(NSString *format, ...) {
    va_list args;
    va_start(args, format);
    NSString *message = [[NSString alloc] initWithFormat:format arguments:args];
    va_end(args);
    NSLog(@"[ABC] %@", message);
}

Mark such functions with NS_FORMAT_FUNCTION(1, 2) so clang checks the format string against the arguments.

Scope and lifetime

Two properties describe a variable: scope (where its name is visible) and lifetime (how long its storage exists).

Kind Declared Scope Lifetime
Local (automatic) inside a function or block that block until the block ends
static local inside a function that function whole program
File-level global outside functions whole file, or whole program if not static whole program
static global outside functions that file only whole program
OBJECTIVEC
int visitCount(void) {
    static int count = 0;   // initialized once, keeps its value between calls
    return ++count;
}

A static local is initialized only once, with a constant expression, and remembers its value. It is how singletons and one-time setup are written: static dispatch_once_t onceToken;.

The storage-class keywords

  • auto is the default for locals, and nobody writes it.
  • register hints that the variable lives in a CPU register; modern compilers ignore it.
  • static gives a local variable permanent storage, or gives a global internal linkage (private to the file).
  • extern declares a global that is defined in another file, as in the constants lesson (extern NSString *const ...).
  • const and volatile are qualifiers rather than storage classes. volatile tells the compiler a value may change outside the program's control, which matters for hardware registers and signal handlers.

Objects declared as locals are pointers, so the pointer disappears at the end of the scope but the object may survive if something else retains it. Under ARC, the compiler releases it when the last strong reference vanishes.

Block scope

Braces create scopes, and an inner declaration can shadow an outer one. Shadowing is legal but a bug magnet; compile with -Wshadow:

OBJECTIVEC
int x = 1;
{
    int x = 2;        // shadows the outer x
    NSLog(@"%d", x);  // 2
}
NSLog(@"%d", x);      // 1

Stand-in: a variadic sum and a nil-terminated list

Both techniques exist in C with the same macros. The second example uses NULL as the terminator, the way Cocoa uses nil.

C Stand-in (C): count-based and NULL-terminated variadics

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: scope and static lifetime

C Stand-in (C): static locals, shadowing and file-level statics

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.

Common mistakes

  • Passing the wrong argument type to a variadic function (for example int where the function reads long).
  • Forgetting the closing nil in a nil-terminated list.
  • Expecting a static local to be initialized on every call.
  • Returning the address of an auto local.
  • Declaring a non-static global in a header, which gives "duplicate symbol" linker errors; use extern there.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does a variadic function know how many arguments it received?

    C does not record the argument count. Conventions such as a count, a format or nil terminate the list.
  2. 2. What is missing from [ABCList listWithItems:@"a", @"b"]?

    The nil-terminated method keeps reading arguments until it sees nil.
  3. 3. When is a static local variable initialized?

    Static locals are initialized once and keep their value between calls.
  4. 4. What does static do to a global function or variable?

    Static at file scope gives internal linkage, so the name is not visible to other files.

Summary

  • ... with <stdarg.h> (va_list, va_start, va_arg, va_end) implements variadic functions.
  • The caller must signal the end of the list: a count, a format string or a trailing nil.
  • Locals die with their scope; static locals and globals live for the whole program.
  • static at file scope hides a name, and extern declares a global defined elsewhere.
  • Avoid shadowing; compile with -Wshadow.

Next: Classes and Objects