gk s
gk s

Reputation: 11

What is the mechanism of returning a structure from a function in C

Could some one please explain, how the structure variable return from a function is implemented. basically when a single variable is returned from a function, the value will be put in a register and return. but in case of structure return, how this will work. I assume that structure will be copied to some global location and return the pointer. This will be managed by compiler. Is my understanding correct ?

This is what my sample program

#include <stdio.h>
#include <stdlib.h>

typedef struct ss
{
  char name[10];
  int val;
} HELLO;


HELLO *ptr=NULL;

HELLO myfun()
{
   HELLO hel = {"Salil", 20};
   ptr = &hel;
   return hel;
}
main()
{

  HELLO hel1;
  hel1 = myfun();
  if ( ptr ) printf("The val = %s \n", ptr->name);
}

Here in myfun, how will the hel variable returned? Where will the variable be kept while returning?

Upvotes: 1

Views: 135

Answers (2)

Chris Dodd
Chris Dodd

Reputation: 126203

It depends on the compiler and the ABI of the target. Some that I have seen:

  • multiple registers: small structs can be returned in several registers in some ABIs

  • global buffer: a buffer can be allocated somewhere that the caller and callee both know about.

  • on stack, caller's frame: the caller can allocate extra space on the stack and pass the address of that space as an hidden extra argument to the function.

  • on stack replacing args: In ABIs where the callee pops args from the stack, it may replace them with the return value.

Upvotes: 3

user1666959
user1666959

Reputation: 1855

You can't return a structure only a pointer to it, provided we are talking about C. Assuming you allocated the space for your struct via malloc/calloc it is the pointer which would be returned. It is difficult to tell whether it would be returned in a register or on the stack, that depends on the optimisation level.

Upvotes: 0

Related Questions