Return a `struct` from a function in C

You can return a structure from a function (or use the = operator) without any problems. It’s a well-defined part of the language. The only problem with struct b = a is that you didn’t provide a complete type. struct MyObj b = a will work just fine. You can pass structures to functions as well – a structure is exactly the same as any built-in type for purposes of parameter passing, return values, and assignment.

Here’s a simple demonstration program that does all three – passes a structure as a parameter, returns a structure from a function, and uses structures in assignment statements:

#include <stdio.h>

struct a {
   int i;
};

struct a f(struct a x)
{
   struct a r = x;
   return r;
}

int main(void)
{
   struct a x = { 12 };
   struct a y = f(x);
   printf("%d\n", y.i);
   return 0;
}

The next example is pretty much exactly the same, but uses the built-in int type for demonstration purposes. The two programs have the same behaviour with respect to pass-by-value for parameter passing, assignment, etc.:

#include <stdio.h>

int f(int x) 
{
  int r = x;
  return r;
}

int main(void)
{
  int x = 12;
  int y = f(x);
  printf("%d\n", y);
  return 0;
}

Leave a Comment