1

In what order should struct (class) members be declared (poetically by name or practically by size)? How to be if struct contains user-defined types? Is it important to order struct members anyway?

struct foo
{
  short data0;
  int   data1;
};

struct bar
{
  int  data0;
  char data1;
  int  data2;
  foo  data3;
};
Ivars
  • 2,375
  • 7
  • 22
  • 31

3 Answers3

3

It's important to order them logically. The order rarely makes a difference in practice. (If you have very large arrays of the object type, and limited memory, arranging them in order of size, from largest to smallest, may result in slightly less memory usage, but in practice, this is rarely and issue.)

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • You might want to add that the order of the members also makes a difference during construction - the order of the members in a constructors initialization list has no effect on the order of construction. This can cause problems in cases where 1 member must be initialized before another (although these scenarios should be avoided wherever possible). – Excelcius Jan 20 '14 at 09:45
  • @Excelcius That's a good point, although he seemed to be asking more about C style `struct` (which of course wouldn't have a constructor). – James Kanze Jan 20 '14 at 11:31
1

If you are not working in memory constrained environment, then organize your members in a logical way - by their responsibilitis, to make it easier to work with. Currently your members have miningless names, so its hard to suggest anything.

If you want to analyze how compiler layouts your structures/classes, you may use tools like /d1reportAllClassLayout (undocumented) compiler parameter in Visual Studio. For your classes it outputs:

1>class foo size(8):
1> +---
1> 0 | data0
1>   | <alignment member> (size=2)
1> 4 | data1
1> +---
1>class bar size(20):
1> +---
1> 0 | data0
1> 4 | data1
1>   | <alignment member> (size=3)
1> 8 | data2
1>12 | foo data3
1> +---

so it looks like 5 bytes are lost due to alignment, you could add additional members in alignment places and it would not require additional memory.

marcinj
  • 48,511
  • 9
  • 79
  • 100
0

Order them for better readability.

The optimal (memory-wise) layout may be:

struct X
{
    short flag1;
    short flag2;
    short flag3;
    short flag4;

    double x;

    short flag5;
}

but it's fairly obvious that it's really unfriendly (considering even more members).

Optimize for space only after it becomes an issue - in which case grouping small ones together up to the larger members would be a starting point.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625