How do you write a function that returns multiple values?
Short answer: C functions return only one value, so either return a struct containing all the results, or return a status code and write the results through pointer parameters (output parameters). Embedded APIs usually use the second form so errors are explicit.
#include <stdint.h>
typedef struct { int16_t x, y, z; } accel_t;
/* 1. return a small struct by value */
accel_t accel_read(void);
/* 2. status + output parameters */
typedef enum { OK = 0, ERR_TIMEOUT, ERR_BUS } status_t;
status_t accel_read2(int16_t *x, int16_t *y, int16_t *z);
/* 3. status + output struct (common and extensible) */
status_t accel_read3(accel_t *out);
/* usage */
accel_t a;
if (accel_read3(&a) != OK) { /* handle error */ }
Trade-offs
| Approach | Pros | Cons |
|---|---|---|
| Return a struct | clean, no pointers, no aliasing issues | no separate error channel (unless the struct has a status field); large structs are copied |
| Output pointers | explicit status, caller owns the memory | callers can pass NULL; function must check |
| Output struct pointer + status | extensible (add fields without changing the signature) | slightly more code |
| Global variables | none worth mentioning | not reentrant, hidden coupling |
Performance: on Arm (AAPCS), a struct of up to 4 bytes is returned in r0; larger structs are returned through a hidden pointer to memory reserved by the caller, so returning a 6-byte accel_t is still cheap. On AArch64, structs up to 16 bytes come back in registers.
Good API habits: document whether outputs are written on failure (usually "not modified" or "undefined"), use const for inputs, and mark the function [[nodiscard]] (C23) or __attribute__((warn_unused_result)) so callers cannot ignore the status.