When to use a union and when to use a structure

后端 未结 4 1995
长情又很酷
长情又很酷 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:27

    You cannot compare unions to structures, it's like comparing apples to oranges, they are used for different things. Unions are typically used in situations where space is premium but more importantly for exclusively alternate data. Unions help eliminate typos and ensure that mutually exclusive states remain mutually exclusive because error in programming logic will surface more quickly when we use unions for mutually exclusive data.

    Also unions can lead to much easier pointer mathematics when working with complex data passing between components. case-in-point when developing compilers with LEX and YACC the values are passed from the lexer to the parser in a union. The parser implementation and subsequent typecasting is made significantly easier because of the use of union.

提交回复
热议问题