Jagdish
Jagdish

Reputation: 1922

What is the purpose of union inside structure here?

typedef struct {
    union {
        u32 slock;
        struct __raw_tickets {
#ifdef __ARMEB__
            u16 next;
            u16 owner;
#else
            u16 owner;
            u16 next;
#endif
        } tickets;
    };                                                                                                                                  
} arch_spinlock_t;

Above is the code snippet from Linux kernel,What is the purpose of putting whole union inside structure, Why not simply union then?

This is the link to source code.

Upvotes: 4

Views: 648

Answers (2)

Matt
Matt

Reputation: 15186

Linux Kernel is a work-in-progress, rather than "see-how-it-should-be-done" thing.

I believe there's no true reason behind this, other than the habit to pack everything in struct's on the top level. If you used to think of "everything is a struct", you may accidently fail by adding some new field to the actual union, not to the struct, as you expected.

Upvotes: 1

Vineet1982
Vineet1982

Reputation: 7918

If I wanted to have several structs which were similar to each other but not identical - that had many common elements but then varied. An example might be a range of products for sale at a shop, where some of the items are sold in int units (I'll sell you one or two motorbikes, but not 1.5) and others are sold in float units (kgs of apples, for example)?

A Union allows you to define a number of different variables, of different types and sizes, in parallel - i.e. sharing the same memory - within a collection.

Used carefully, a union within a struct can be used to produce a collection that can handle a whole family of slightly varied data types, such as the motorbikes and apples.

C's unions let you define a block of memory which has two (or more) names associated with it so that - when combined with structs - you can produce a whole family of defined variable types based on a common core, but then varying in parts where appropriate.

Edit: Adding Example

typedef union {
    int units;
    float kgs;
} amount ;

typedef struct {
    char selling[15];
    float unitprice;
    int unittype;
    amount howmuch;
} product;

Upvotes: 0

Related Questions