-1

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

vinzee
  • 17,022
  • 14
  • 42
  • 60
Csharp
  • 2,820
  • 15
  • 47
  • 77

4 Answers4

2

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,007
  • 13
  • 28
1

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.

mtasic85
  • 3,684
  • 2
  • 18
  • 28
1

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
  • 27,783
  • 3
  • 71
  • 117
0

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
  • 61,188
  • 17
  • 100
  • 153