C編譯器如何傳遞並從函數返回struct/union?在函數調用之前,結構是否被推入堆棧,只有傳遞給該函數的結構引用?將struct/union傳遞給C中的函數C
同樣的問題適用於退貨。函數返回的是什麼?
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);
}
這是我的猜測(僞代碼):
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()
或者另一種解決方案可能是:
call transfer(&x)
y.array[0] = shift_stack()
y.array[1] = shift_stack()
y.array[2] = shift_stack()
y.array[3] = shift_stack()
它取決於實現。通常實施將遵循平臺ABI。 – 2014-11-06 09:11:44