c / intermediate
Snippet
Returning Multiple Values via Pointers
Since C functions return only one value, pointers are used as 'output parameters'. By passing the address of local variables, the function can write results directly into the caller's stack frame.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>void calculate_stats(int a, int b, int *sum, int *diff) {if (sum) *sum = a + b;if (diff) *diff = a - b;}int main(void) {int s, d;calculate_stats(15, 5, &s, &d);printf("Sum: %d, Difference: %d\n", s, d);return 0;}
Breakdown
1
int *sum
A pointer used to receive a memory address from the caller.
2
*sum = a + b
Dereferences the pointer to store the result in the caller's variable.