c - What is there to be gained by deterministic field ordering in the memory layout? -


members of structure allocated within structure in order of appearance in declaration , have ascending addresses.

i faced following dilemma: when need declare structure,

(1) group fields logically, or

(2) in decreasing size order, save ram , rom size?

here example, largest data member should @ top, should grouped logically-connected colour:

struct pixel{     int posx;     int posy;      tlargetype colourspacesecretformula;     char colourrgb[3]; } 

the padding of structure non-deterministic (that is, implementation-dependent), cannot reliably pointer arithmetic on structure elements (and shouldn't: imagine reordering fields liking: boom, whole code stops working).

-fpack-structs solves in gcc, bears other limitations, let's leave compiler options out of question.

on other hand, code should be, above all, readable. micro optimizations avoided @ cost.

so, wonder, why structures' members ordered standard, making me worry micro-optimization of ordering struct member in specific way?

the compiler limited several traditional , practical limitations.

the pointer struct after cast (the standard calls "suitably converted") equal pointer first element of struct. has been used implement overloading of messages in message passing. in case struct has first element describes type , size rest of struct is.

the last element can dynamically resized array. before official language support has been used in practice. allocate sizeof(struct) + length of data , can access last element normal array many elements allocated.

those 2 things force compiler have first , last elements in struct in same order declared.

another practical requirement every compilation must order struct members same way. smart compiler make decision since sees struct members accessed close each other reordered in way makes them end in cache line. optimization of course impossible in c because structs define api between different compilation units , can't reorder things differently on different compilations.

the best given limitations define kind of packing order in abi minimize alignment waste doesn't touch first or last element in struct, complex, error prone , wouldn't buy much.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -