Can anyone provide a realworld example of when a struct can be used?
4 Answers
A struct can be used when you have a complex return type for a method. i.e. you have to return several values, and they don't really warrant a full class's overhead.

- 1,025
- 13
- 28
A struct is notion of a record, a datatype that aggregates a fixed set of labelled objects, possibly of different types, into a single object. Structs are often used to group and relate objects in some manner.

- 3,905
- 2
- 19
- 28
If you mean a C struct, a great example is fixed scalar types in compilers. For example:
struct myScalar {
void *payload;
size_t psz;
unsigned int refs;
enum {
S_STR,
S_INT,
S_FLOAT,
S_OBJECT_INSTANCE
}type;
};
Or a union could be used. Not a robust example, but you get the idea. You can then do
switch(aVar.type){ ... }

- 28,212
- 4
- 75
- 119
Structs are great for helping you parse data that has been compressed to bits for sending over "The wire". You might have a bunch of bitfields to fill out a single byte, and a struct is a way to lay a template over this scrambled pile of variables and, without any real effort, change it into a collection of usable, easily referenced variables.

- 62,186
- 18
- 105
- 157