3 ms·
Don't elements of structures are sorted before even packing starts? For example char c; int i; char c2; I thought in reality c2 starts after c. Instead o
by shultays 12y ago
Don't elements of structures are sorted before even packing starts? For example
char c;
int i;
char c2;
I thought in reality c2 starts after c. Instead of adding padding between each element, you will only need in boundaries
- alepper 12y agoNo, the standard requires they appear in their order of declaration.
- wila 12y agoThe compiler doesn't care much how your structure element is named. The naming scheme is for the benefit of the developer. Once the program is compiled the variable is referenced by memory address, not variable name. Sorting them by name would not help there.
- dlp211 12y agoI don't think (s)he meant sorted alphabetically, but rather, sorted in such a way as to minimize memory usage, ie: packed. This is obviously not the default in C, but can be enabled via compiler extensions. It's also important that the compiler doesn't automatically do this since structs of the same type can be of different sizes. In order for this to work, the memory layout needs to be as originally defined in order to be correct. For an example of this see the simple dynamic string library used in redis.
- wongarsu 12y agoThat would be bad in all kinds of situations which depend on one specific ordering of fields. When you use structs for inter-process communication in shared memory or inside memory-mapped device memory you care a lot about defining your own order. When writing structs verbatim to network or disk (or reading that way) automatic reordering would quickly break things too.