Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 26 / 68

Writing a variadic function

This lesson covers writing a variadic function in Objective-C, with the aim of producing functions that accept any number of arguments.

C's stdarg.h lets you write a variadic function that takes any number of arguments — picture a bag that holds however much you put in. NSLog() itself is built this way.

The sample code uses the macros va_list, va_start, va_arg, and va_end so that a sum() function takes the arguments out in turn and totals them. Note that this C mechanism works unchanged in Objective-C.

A common early stumble is that the program has no way of knowing the type or number of the arguments. Get either wrong at the call site and you have a serious bug.

In professional work, this mechanism is used where values of varying kind and number are handled together, as in a logging function.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Objective-C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)