🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Return Structure From Function
Free C Programming Course for Embedded Systems · Structure and Union · Lecture 18
A C function normally returns one value. In this lecture of our free C programming course you learn how to return a structure from a function in C, which is the clean way to hand back several related values at once. This is a favourite technique in embedded C programming for returning a status together with a result, or a time value, or a coordinate pair, without global variables.
If you are working through this free embedded C course in order, you already know that structures are copied when passed. Returning is the same idea in the other direction.
Table of Contents
What You Will Learn
After this lecture you can:
- Write a function whose return type is a structure.
- Assign the returned structure to a variable of the same type.
- Return a result and an error status together without globals.
- Explain what the compiler does to return a structure.
- Choose between returning a structure and filling a caller-supplied one.
Prerequisites
You need structure basics, the copy behaviour from lecture 16, and the usual function syntax. Knowing about uint8_t and friends from stdint.h helps but is not required here.
How Returning a Structure Works
A structure is an ordinary object in C, so it can be the return type of a function. Inside the function you build a local structure, fill its members, and write return local;. The caller then assigns the returned value to its own variable of the same type. Behind the scenes the contents are copied to the caller. The local variable disappears when the function returns, but because its contents were copied, nothing dangles.
Returning a structure by value
Contrast with returning a pointer
Returning a copy of a local structure is safe. Returning the address of a local structure is a serious bug. We study that difference in the next lecture.
Example 1: Clock Time Arithmetic
An RTC driver often needs to add a number of seconds to a time of day and wrap around midnight. The function takes a time structure and a delta, and returns the new time. The input is not modified, which makes the function easy to reason about and test.
#include <stdio.h>
struct clock_time {
unsigned hh;
unsigned mm;
unsigned ss;
};
struct parse_result {
int status; /* 0 = ok, -1 = error */
int value;
};
static struct clock_time add_seconds(struct clock_time t, unsigned secs)
{
unsigned total = t.hh * 3600u + t.mm * 60u + t.ss + secs;
struct clock_time out;
out.hh = (total / 3600u) % 24u;
out.mm = (total % 3600u) / 60u;
out.ss = total % 60u;
return out;
}
static struct parse_result safe_divide(int a, int b)
{
struct parse_result r = { -1, 0 };
if (b != 0) {
r.status = 0;
r.value = a / b;
}
return r;
}
int main(void)
{
struct clock_time now = { 23, 59, 30 };
struct clock_time later = add_seconds(now, 45);
printf("now = %02u:%02u:%02u\n", now.hh, now.mm, now.ss);
printf("later = %02u:%02u:%02u\n", later.hh, later.mm, later.ss);
struct parse_result ok = safe_divide(100, 8);
struct parse_result bad = safe_divide(100, 0);
printf("100/8 -> status=%d value=%d\n", ok.status, ok.value);
printf("100/0 -> status=%d value=%d\n", bad.status, bad.value);
return 0;
}
Build and run:
gcc -std=c11 -Wall -Wextra -o ret_struct ret_struct.c
./ret_struct
Expected output:
now = 23:59:30
later = 00:00:15
100/8 -> status=0 value=12
100/0 -> status=-1 value=0
Notice that now is unchanged after the call. The function received a copy, built a new structure, and returned it. 23:59:30 plus 45 seconds crosses midnight and wraps to 00:00:15, which the modulo by 24 hours handles.
Example 2: Status Plus Value
C has no exceptions and no tuples. When a function can fail, there are three common styles: return an error code and write the result through a pointer, set a global such as errno, or return a small structure containing both. The second program above uses the third style. The caller always receives an answer and a status in one step, so ignoring the error requires an explicit choice to ignore status.
| Style | Pros | Cons |
|---|---|---|
| Return struct {status, value} | Self-contained, no globals, easy to test | Copy cost for bigger results |
| Error code plus output pointer | No copy of the result | Caller must declare a variable first |
| Global error variable | Short call sites | Not reentrant, hides data flow |
Return by Value vs Output Pointer
Returning a structure reads beautifully, but remember it copies. For small results of eight to sixteen bytes it is excellent, and modern compilers can often build the result directly in the caller’s memory, avoiding a second copy. For large results, such as a structure holding a 256-byte buffer, prefer an output pointer so the data is written exactly once in its final location.
| Result size | Recommended style |
|---|---|
| A few bytes (pair, time, status+value) | Return the structure |
| Dozens of bytes | Either; measure on target |
| Hundreds of bytes or arrays | Output pointer parameter |
Assigning Structures
The statement later = add_seconds(now, 45); works because structures of the same type can be assigned to each other with a plain =. Arrays cannot, which is why wrapping an array in a structure is sometimes used as a trick to copy it. You cannot assign between two different structure types even if their members match.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Ignoring the returned structure | Result lost, a compiler warning may appear | Assign it to a variable |
| Assigning to a different structure type | Compile error | Use one type everywhere |
| Leaving members uninitialised in the returned structure | Garbage values reach the caller | Initialise every member, or the whole structure first |
| Not checking the status member | Bad value used silently | Test status before using value |
| Returning very large structures from hot paths | Slow, stack heavy | Use an output pointer |
Best Practices
- Initialise a result structure completely, including the error path, before returning.
- Keep returned structures small; use an output pointer beyond that.
- Make status values named constants or an enum rather than bare numbers.
- Write functions that take and return structures without side effects; they are simple to unit test on a PC.
- Compile with
-Wall -Wextraso unused results and uninitialised members get flagged.
Summary and Conclusion
Key Takeaways
- A function can return a whole structure, and the caller assigns it to a variable of the same type.
- The return value is a copy, so it is safe even though the local variable disappears.
- A status-plus-value structure is a neat way to report errors in C.
- Prefer an output pointer when the result is large.
You can now return a structure from a function in C and use it to pass back results and errors in one object. The next lecture of this free C tutorial covers returning a pointer to a structure, where memory ownership becomes the main concern.
Suggested Images
- Diagram of a structure copied from a function frame to the caller. ALT: return structure from function in C diagram, free C programming course
- Output screenshot of the clock example wrapping past midnight. ALT: embedded C programming return structure example output, free embedded C course
Frequently Asked Questions
Can a C function return a structure?
Yes. Declare the return type as the structure type and return a structure value.
Is it safe to return a local structure?
Yes, because the contents are copied to the caller. Returning the address of a local is what is unsafe.
How can I return two values from a C function?
Return a small structure containing both, or use output pointers.
Can I assign one structure to another?
Yes, if both have the same type. All members are copied.
Is returning a structure slow on a microcontroller?
For small structures it is cheap. For large ones use an output pointer to avoid the copy.
Should I use this in an interrupt handler?
Prefer small results and avoid large copies, since interrupt stacks are small.
Keep Going with the Free Embedded C Course
Next up in this free C tutorial: returning a pointer to a structure and managing its memory.

2 Comments