Page 1 of 1

c: functions returning a struct

Posted: Fri May 13, 2005 8:33 am
by Adek336
Hi :)
A function returning a struct is given a pointer where it copies the return value. Now, is there a language construct for returning a struct filled with zeroes?
And if a function's formal parameter is a struct, is it given by value or by address?

Cheers :)

Re:c: functions returning a struct

Posted: Fri May 13, 2005 8:41 am
by Solar
Adek336 wrote:A function returning a struct is given a pointer where it copies the return value.
That wouldn't work, as you cannot return a struct by value that you received by pointer. You could perhaps return a copy of that struct, but that struct and the one pointed to by the pointer wouldn't be the same object.

You could make the function return the pointer to the struct...
Now, is there a language construct for returning a struct filled with zeroes?
AFAIK an automatically created struct is zero-initialized by default, but I'm not sure.

Re:c: functions returning a struct

Posted: Fri May 13, 2005 9:12 am
by Adek336
Thanks for you reply Solar :)

I think I was somewhat unclear.
A function returning a struct is given a pointer where it copies the return value.
Well, I mean, in the disassembly of something like the following

Code: Select all

struct x { int a; .. };
struct x myFun ()
 {
struct x u;
   u.a=1;
   return u;
 }
int main()
 {
struct x v= myFun();
 }
it looked like main allocated v on stack and then passed a pointer to it using %eax, while myFun allocated u on stack, manipulate it and copy the contents of u to v.

I'm not sure, though. Well anyways I found a neat way for returning an empty struct:

Code: Select all

struct x
 {
  int a;
  a (int val) { memset(this, val, sizeof(x)); }
 }
struct x NullX() {
   return (struct x) 0;
 }
In the mean-time, I decided my function would return a pointer as I do not need a copy of the bios32 directory service header.

Cheers :)

Re:c: functions returning a struct

Posted: Fri May 13, 2005 9:25 am
by Colonel Kernel
Solar wrote:
Now, is there a language construct for returning a struct filled with zeroes?
AFAIK an automatically created struct is zero-initialized by default, but I'm not sure.
I don't have a source handy, but my gut says no.