tags:

views:

114

answers:

4

can anyone provide a realworld example of when a struct can be used?

+2  A: 

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.

GreenKiwi
+1  A: 

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.

mtasic
A: 

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.

Bill K
+1  A: 

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){ ... }
Aiden Bell