The Psychology of Quality and More
CHAPTER 9 : Data Usage
9.5 Using Structures
Structures are one of the most powerful tools in C for organizing data, provided that they are used sensibly and carefully.
9.5.1 Keep them cohesive
Collecting data in a structure gives a message: "The data within this structure is highly cohesive." That is, the data is collected using a common rule, typically that the data collectively describes a single complex object:
Note that the description need not be complete in every detail, although it should contain all of the information about that object that will be needed.
9.5.2 Nesting structures
When data naturally breaks down into sub-items, then it is logical to nest the information also:
Nesting shows the clear relationship between the structures, whilst also showing their individual identities. This can, however, make the overall declaration more complex, especially if there are several levels of nesting. A simplification is to separate out the nested structures:
A common alternative to nesting structures is nesting pointers to structures. It can be confusing if you have a mixture of nested structures and pointers:
A simpler approach is to stick to one type of nesting. Pointers are more flexible, although they need more initialization:
There is a danger with large structures as, when they are passed as parameters, only a small part may be used by any one function. A bug in the called function could cause corruption of the other structure data, which may not become apparent until some considerable time later (this type of problem is very difficult to fix!). Such 'tramp data' can be minimized by nesting the structure, as above, and only passing the relevant parts:
BrickVol = CalcVolume( &Brick.Size );
And the big