Step 3 of 10
Returning two results
A function can only return one value. When it naturally produces several results, a common C pattern is out parameters: the caller passes the addresses of variables, and the function fills them in.
#include <stdio.h>
void min_max(const int a[], int n, int *min, int *max) {
*min = a[0];
*max = a[0];
for (int i = 1; i < n; i++) {
if (a[i] < *min) {
*min = a[i];
}
if (a[i] > *max) {
*max = a[i];
}
}
}
int main(void) {
int data[] = {7, -2, 15, 4};
int lo, hi;
min_max(data, 4, &lo, &hi);
printf("min %d, max %d\n", lo, hi);
return 0;
}
min -2, max 15
Reading the pattern
- The parameters
int *minandint *maxare "where to put the answers". - Inside, the function writes through them:
*min = .... - The caller creates the variables (
lo,hi), then passes their addresses.
Out parameters show up all over real C code, including the standard library. A frequent combination is to return a success or error code while delivering the actual results through pointers, so the caller can check whether it worked.
Name out parameters clearly and write to every one of them on every path, so the caller never reads an unset variable.
Your task
Write void divmod(int a, int b, int *q, int *r) that stores a / b in *q and a % b in *r.
Challenge 2
Write void min_max(const int a[], int n, int *min, int *max) that stores the smallest and the largest element of the array (which has at least one element) in *min and *max.
Challenge 3
Write int stats(const int a[], int n, int *sum, double *avg). If n is 0, return 0 and don't touch *sum or *avg. Otherwise store the sum and the average and return 1. Returning a success flag like this is a common C pattern.
Previous: Change the caller's variable Next: Pointer arithmetic and arrays