Selecting Behavior with Function Pointers
Function pointers let a C program choose an operation while it runs. A function pointer is a pointer value that identifies a function of a particular type. You can store that value in a variable, replace it with another compatible function pointer, or pass it to a helper. Assigning a function pointer does not execute the function; execution happens when you make a call.
Reading the declaration
Consider this declaration:
int (*op)(int);Read outward from op: (*op) makes it a pointer, (int) describes the function's parameter, and the leading int gives its return type. The parentheses around *op matter because function-call parentheses bind more tightly than the pointer declarator.
Declaration | Meaning |
|---|---|
int (*op)(int); | A pointer to a function taking an integer and returning an integer |
int *op(int); | A function taking an integer and returning a pointer to an integer |
int (*ops[3])(int); | An array of three pointers to functions taking an integer and returning an integer |
A function prototype lets the compiler check the argument and return types used through a function pointer. For these simple declarations, compatible targets have the same return type and corresponding parameter types.
Storing, selecting, and calling
Example: Suppose two functions implement different integer transformations.
int increment(int x) { return x + 1; }
int twice(int x) { return 2 * x; }Inside a caller function, you can write:
int (*op)(int) = increment;
int a = op(4);
op = twice;
int b = (*op)(4);When used as a value here, the function name increment converts to a pointer to that function. Writing &increment would select the same target. By contrast, increment(4) calls the function and produces an integer.
For a function that transforms one input, the governing idea is:
Both op(4) and (*op)(4) call the function currently selected by op. In the code above, a becomes 5. After reassignment, b becomes 8. Reassignment changes later calls; it does not change an earlier result or either function's body.
An array of function pointers can select an operation by index. Initialize its entries, check that an index is within the array's bounds, and ensure that the selected entry is callable before invoking it. Function pointers support equality comparisons, but arithmetic such as op + 1 is not permitted in ISO C.
Passing behavior to a helper
A callback is a function supplied to another function so that the receiving function can invoke it. A type alias can make the parameter declaration easier to read:
typedef int (*Unary)(int);
int apply(Unary fn, int x) {
return fn(x);
}Unary already names a pointer type. The parameter fn receives a function pointer value, so the helper can call it using ordinary call syntax. Calling apply(twice, 7) returns 14. The helper supplies the calling procedure; its argument selects the operation.
Before calling through a pointer, it must have an initialized, non-null value identifying an appropriate function. Testing op != 0 checks for a null pointer, but it does not establish type compatibility.
Check the actual function type, not just the spelling of a cast. When a helper receives a function pointer by value, reassigning that parameter changes the helper's local selection; it does not reassign the caller's pointer variable.
What to remember
- Parentheses distinguish a function pointer from a function returning a pointer.
- A function name selects a function; adding arguments calls it.
- op(x) and (*op)(x) invoke the currently selected function.
- Type aliases simplify callbacks and arrays without adding pointer levels.
- Call only through an initialized, non-null pointer with a compatible function type.
Example: Choosing a Courier Fee Function
Example: A courier quotes delivery fees using a dispatch table, an array of function pointers whose entries select different operations. Each fee function accepts a package weight in kilograms and returns an integer number of cents. For this example, weights are nonnegative whole kilograms, and the stated formulas include the entire fee.
int standard(int kg) {
return 300 + 80 * kg;
}
int priority(int kg) {
return 650 + 120 * kg;
}
int combined_fee(int first, int second, int (*fee)(int)) {
return fee(first) + fee(second);
}Perform the following selections inside a caller function.
a) Define Fee as a type alias for a pointer to either fee function. Declare a two-entry array services, with standard first and priority second, and initialize a pointer named selected from the first entry.
Both targets take one integer and return one integer. The alias must therefore represent a pointer to a function with that parameter and return type. Parentheses around *Fee distinguish this from a function returning a pointer.
typedef int (*Fee)(int);
Fee services[2] = {standard, priority};
Fee selected = services[0];The function names initialize the entries with function pointers; they do not calculate fees. Index zero selects standard, so selected initially points to standard.
b) Evaluate selected(6). Then execute selected = services[1]; and evaluate selected(6) again. State both fees in cents.
Initially, selected points to standard. Its rate is 80 cents per kilogram, so the weight-dependent portion for 6 kg is ________. Adding the fixed fee gives:
The reassignment selects priority for the next call. Its weight-dependent portion is ________, so:
The two calls return 780 cents and 1370 cents, respectively. Reassignment changes the selected function without changing the argument or either fee formula.
c) Evaluate combined_fee(2, 5, services[1]). Identify the function invoked by the helper and state the total in cents.
The array entry services[1] contains a pointer to priority. Passing that entry supplies the helper's fee parameter; it does not invoke the fee function yet.
The helper's first call computes the fee for 2 kg:
This first fee is ________. Its second call computes the fee for 5 kg:
This second fee is ________. Each package incurs its own fixed charge, because the helper calls the complete fee function once for each package. It then adds the results:
The helper invokes priority twice and returns 2140 cents. Adding the weights before making a single call would incorrectly charge the fixed fee only once.
The standard library function qsort can sort an array of any element type because the caller passes it a function pointer as its fourth argument. The comparator below is used to sort an int array of exam scores into ascending order. Fill each blank with one word from this list: callback, element, index, negative, positive, zero.
int by_score(const void *a, const void *b)
{
int x = *(const int *)a;
int y = *(const int *)b;
return (x > y) - (y > x);
}
qsort(scores, count, sizeof scores[0], by_score);A function that your code hands to qsort so that qsort can call it later is a . Each of its two const void * parameters points to one array , not to a position number. To place the first item before the second, the comparator must return a value, and it returns when the two items are equivalent.
A dispatch table is an array of function pointers used to select an operation by index. In the following C program, what is the value of result immediately before main returns? Give an exact integer with zero decimal places.
int lower(int x) { return x - 4; }
int scale(int x) { return 3 * x; }
typedef int (*Unary)(int);
int main(void) {
Unary ops[2] = {lower, scale};
Unary f = ops[1];
int result = f(7);
f = ops[0];
result = f(result);
return result;
}