nowox
nowox

Reputation: 29096

Passing struct/union to a function in C

How does the C compiler pass and return struct/union to/from a function? Is the struct pushed to the stack before the function call is it only the struct's reference that is passed to the function?

The same question applies for the return. What does the function return exactly?

typedef struct {
    long m4;
    long m3;
    long m2;
    long m1;
} ext_components_t;

typedef union { 
    long array[sizeof(int_components_t)];
    int_components_t comp;
} int_components_u;

typedef union {
    long array[sizeof(ext_components_t)];
    ext_components_t comp;
} ext_components_u;

#pragma never_inline
ext_components_u transfer(int_components_u m) 
{
    ext_components_u out;
    out.comp.m1 = 10*m.comp.a+11*m.comp.b+12*m.comp.c;
    out.comp.m2 = 20*m.comp.a+21*m.comp.b+22*m.comp.c;
    out.comp.m3 = 30*m.comp.a+31*m.comp.b+32*m.comp.c;
    out.comp.m4 = 40*m.comp.a+41*m.comp.b+42*m.comp.c;
    return out;
}

volatile int_components_u x;
volatile ext_components_u y;
void main()
{
    y = transfer(x);
}

Here's my guess (pseudo code):

push_stack(x.array[0])
push_stack(x.array[1])
push_stack(x.array[2])

call transfer

y.array[0] = shift_stack()
y.array[1] = shift_stack()
y.array[2] = shift_stack()
y.array[3] = shift_stack()

Or another solution could be:

call transfer(&x)
y.array[0] = shift_stack()
y.array[1] = shift_stack()
y.array[2] = shift_stack()
y.array[3] = shift_stack()

Upvotes: 1

Views: 1927

Answers (2)

Mohit Jain
Mohit Jain

Reputation: 30489

How to pass the structs and return the structs is implementation dependent. Usually they are copied on stack. Parameters are passed in registers (for speed) wherever possible.

An implementation may pass an int and a struct containing only int member in different manner. Same rules apply to unions also.

Some books say that "parameters are passed to a called function by pushing them on the stack from right to left". This is oversimplication. (From Expert C programming Deep C secrets by Peter Van der Linden)

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409166

In C all arguments to functions are passed by value. That means that structures and unions are copied when passed to functions. How that copying is handled is implementation specific, but the most common way is to allocate space on the stack and copy the contents of the structure/union into that space.

The same goes for returning data, it's returned by value (i.e. copied).


There's an important thing to note here, and that is that C doesn't have pass by reference. When you pass a pointer, it's the pointer that is passed by value, i.e. it's copied.

However, you can use pointers to emulate passing by reference.

Upvotes: 7

Related Questions