Actual usage of union in C [duplicate]

﹥>﹥吖頭↗ 提交于 2019-12-06 07:49:34

问题


Possible Duplicate:
C: Where is union practically used?

I know the concept of union but I don't see the actual case in real world coding that I should use union data structure. I will be very appreciated if you guys can give me some examples or tutorials that shows cases using union properly.

Thanks in advance.


回答1:


Where I use it constantly: parsing a configuration file I store all values in a union data type. E.g. when values can be int types or strings, I would use a data structure as follows:

struct cval_s {
  short type;
  union {
    int ival;
    char *cval;
  } val;
};

In complexer problems, I use them, too. E.g. once I wrote an interpreter for an easy scripting language, and a value in this language was represented by a struct containing a union.




回答2:


Imagine having a struct that keeps a value and the type of that value. When the type is set to a particular type, you would only need to use one of the members of the union rather than waste space for three of them when you use only one simultaneously.

struct {
  int type;

  union {
    int intval;
    double dval;
    char cval;
  } value;
}


来源:https://stackoverflow.com/questions/6303360/actual-usage-of-union-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!