Actual usage of union in C [duplicate]

≯℡__Kan透↙ 提交于 2019-12-04 14:36:56

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.

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