Using structures

can anyone provide a real world example of when a structure can be used?

0


a source to share


4 answers


A struct can be used when you have a complex return type for a method. those. you need to return multiple values ​​and they don't really require the class overhead.



+2


a source


A structure is the concept of a record, a data type that combines a fixed set of labeled objects, possibly of different types, into one object. Structures are often used to group and match objects in some way.



+1


a source


If you mean a C structure, a great example is the fixed scalar types in compilers. For instance:

struct myScalar {
    void *payload;
    size_t psz;
    unsigned int refs;
    enum {
        S_STR,
        S_INT,
        S_FLOAT,
        S_OBJECT_INSTANCE
    }type;
};

      

Or you can use a union. Not a solid example, but you get the idea. Then you can do

switch(aVar.type){ ... }

      

+1


a source


Structures are great for helping you parse data compressed into bits for sending over the Wire. You can have many bitfields to fill a single byte, and structure is a way to lay a template over that scrambled bunch of variables and, without any real effort, change it to a set of usable, easily referenced variables.

0


a source







All Articles