c: functions returning a struct

Programming, for all ages and all languages.
Post Reply
Adek336

c: functions returning a struct

Post 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 :)
User avatar
Solar
Member
Member
Posts: 7615
Joined: Thu Nov 16, 2006 12:01 pm
Location: Germany
Contact:

Re:c: functions returning a struct

Post 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.
Every good solution is obvious once you've found it.
Adek336

Re:c: functions returning a struct

Post 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 :)
User avatar
Colonel Kernel
Member
Member
Posts: 1437
Joined: Tue Oct 17, 2006 6:06 pm
Location: Vancouver, BC, Canada
Contact:

Re:c: functions returning a struct

Post 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.
Top three reasons why my OS project died:
  1. Too much overtime at work
  2. Got married
  3. My brain got stuck in an infinite loop while trying to design the memory manager
Don't let this happen to you!
Post Reply