When to use a union and when to use a structure

后端 未结 4 2005
长情又很酷
长情又很酷 2021-01-01 03:24

I know the differences between union and structure. But from a design and coding perspective what are the various use cases of using a union instead of a structure? One is a

4条回答
  •  没有蜡笔的小新
    2021-01-01 04:01

    You use a union when your "thing" can be one of many different things but only one at a time.

    You use a structure when your "thing" should be a group of other things.

    For example, a union can be used for representing widgets or gizmos (with a field allowing us to know what it is), something like:

    struct {
        int isAGizmo;
        union {
            widget w;
            gizmo g;
        }
    }
    

    In this example, w and g will overlap in memory.

    I've seen this used in compilers where a token can be a numeric constant, keyword, variable name, string, and many other lexical elements (but, of course, each token is one of those things, you cannot have a single token that is both a variable name and a numeric constant).

    Alternately, it may be illegal for you to process gizmos without widgets, in which case you could use:

    struct {
        widget w;
        gizmo g;
    }
    

    In this case, g would be at a distinct memory location, somewhere after w (no overlap).

    Use cases for this abound, such as structures containing record layouts for your phone book application which will no doubt earn you gazillions of dollars from your preferred app store :-)

提交回复
热议问题