Tell me more ×

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

share|improve this question
As in a C struct? –  Aiden Bell May 21 '09 at 17:13
add comment

closed as not a real question by Jon B, dfa, Neil Butterworth, Lasse V. Karlsen, Daniel A. White May 21 '09 at 17:16


4 Answers

up vote 2 down vote accepted

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

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 {

Or a union could be used. Not a robust example, but you get the idea. You can then do

switch(aVar.type){ ... }
share|improve this answer
add comment

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.

share|improve this answer
add comment
