Course contentsShow
← C
Lesson 606 of 1,2199. Structures and UnionsFree lesson

Returning a struct from a function

Returning a struct from a function

What you'll learn: How to send a complete bundle of related data back from a function using a single return statement.

The Power of the Bundle

Imagine you are at a fast-food drive-thru. You don't just order a patty, then a bun, then lettuce, and receive them one by one. You order a "Combo Meal," and the attendant hands you a single bag containing everything.

In C, functions usually return only one thing, like an int or a float. However, because a struct is a custom data type that acts as a single container, you can use it to return multiple related values at once. This keeps your code organized and prevents you from having to use confusing workarounds.

How It Works

When you return a struct, the function creates a copy of the entire structure and sends it back to the caller. The return type of your function must match the name of the struct you defined.

Here is a simple example involving coordinates on a map:

#include <stdio.h>

// Define the structure
struct Point {
    int x;
    int y;
};

// A function that returns a Point struct
struct Point createPoint(int xValue, int yValue) {
    struct Point newPoint;
    newPoint.x = xValue;
    newPoint.y = yValue;
    
    return newPoint; // Sending the whole "bag" back
}

int main() {
    // Receive the returned struct into a variable
    struct Point myLocation = createPoint(10, 25);
    
    printf("Location: %d, %d\n", myLocation.x, myLocation.y);
    return 0;
}

Why use this?

In the example above, without a struct, you would have to write two separate functions to get x and y, or use advanced pointer logic. By returning the struct, you treat the coordinates as a single unit.

One important thing to remember: when a function returns a struct, C performs a "shallow copy." This means it copies all the values inside the struct one by one into the receiving variable. It is a clean, efficient way to move small to medium amounts of related data around your program.

Key takeaway

A function can return a struct just like a standard variable, allowing you to pass multiple pieces of data back to your main code in a single, organized package.