原文网址:http://www.tutorialspoint.com/cprogramming/c_unions.htm

A union is a special data type available in C that enables you to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multi-purpose.

Defining a Union

To define a union, you must use the union statement in very similar was as you did while defining structure. The union statement defines a new data type, with more than one member for your program. The format of the union statement is as follows:

union [union tag]
{member definition;member definition;...member definition;
} [one or more union variables];  

The union tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you can specify one or more union variables but it is optional. Here is the way you would define a union type named Data which has the three members i, f, and str:

union Data
{int i;float f;char  str[20];
} data;  

Now, a variable of Data type can store an integer, a floating-point number, or a string of characters. This means that a single variable ie. same memory location can be used to store multiple types of data. You can use any built-in or user defined data types inside a union based on your requirement.

The memory occupied by a union will be large enough to hold the largest member of the union. For example, in above example Data type will occupy 20 bytes of memory space because this is the maximum space which can be occupied by character string. Following is the example which will display total memory size occupied by the above union:

#include <stdio.h>
#include <string.h>union Data
{int i;float f;char  str[20];
};int main( )
{union Data data;        printf( "Memory size occupied by data : %d\n", sizeof(data));return 0;
}

When the above code is compiled and executed, it produces the following result:

Memory size occupied by data : 20

Accessing Union Members

To access any member of a union, we use the member access operator (.). The member access operator is coded as a period between the union variable name and the union member that we wish to access. You would use union keyword to define variables of union type. Following is the example to explain usage of union:

#include <stdio.h>
#include <string.h>union Data
{int i;float f;char  str[20];
};int main( )
{union Data data;        data.i = 10;data.f = 220.5;strcpy( data.str, "C Programming");printf( "data.i : %d\n", data.i);printf( "data.f : %f\n", data.f);printf( "data.str : %s\n", data.str);return 0;
}

When the above code is compiled and executed, it produces the following result:

data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming

Here, we can see that values of i and f members of union got corrupted because final value assigned to the variable has occupied the memory location and this is the reason that the value if str member is getting printed very well. Now let's look into the same example once again where we will use one variable at a time which is the main purpose of having union:

#include <stdio.h>
#include <string.h>union Data
{int i;float f;char  str[20];
};int main( )
{union Data data;        data.i = 10;printf( "data.i : %d\n", data.i);data.f = 220.5;printf( "data.f : %f\n", data.f);strcpy( data.str, "C Programming");printf( "data.str : %s\n", data.str);return 0;
}

When the above code is compiled and executed, it produces the following result:

data.i : 10
data.f : 220.500000
data.str : C Programming

Here, all the members are getting printed very well because one member is being used at a time.

C - Unions相关推荐

  1. c语言联合体作用,C语言 联合体(Unions)

    C语言 联合体(Unions) 联合体是C语言中可用的特殊数据类型,它允许将不同的数据类型存储在同一内存位置. 定义联合体 联合体,您必须以与定义结构相同的方式使用 union 语句, union语句 ...

  2. 结合实例学习F#(二) --基本数据类型Discriminated Unions

    题外话: 我写这个主要是希望更多的.Net开发人员能了解F#,能在看到F#代码时不被一堆奇怪的符号搞晕(其实也没几个奇怪的符号).我没有说过F#比别的语言好.会取代C#之类的话,只是希望更多的人能了解 ...

  3. C语言第五章Structures Unions

    文章目录 Structures Declarations Using Structures Accessing Structure Members Using typedef Working With ...

  4. android sqlite union,SQLite Unions 子句

    SQLite Unions 子句 SQLite的 UNION 子句/运算符用于合并两个或多个 SELECT 语句的结果,不返回任何重复的行. 为了使用 UNION,每个 SELECT 被选择的列数必须 ...

  5. typescript 文档阅读笔记-Unions and Intersection Types

    Union Types 用来组合不同类型 let name: string | number Unions with Common Fields 如果某个值的类型是一个联合类型.那么我们只能访问他们公 ...

  6. 关于Avro中的Unions类型

    Avro中的复杂类型 Avro支持六种复杂类型: records enums arrays maps unions fixed Unions类型介绍 Unions使用JSON数组表示. 例如,[&qu ...

  7. 解决keil_mdk编译error: #3092: anonymous unions are only supported in --gnu mode

    extern struct STRUCT_USARTx_Fram {char Data_RX_BUF[RX_BUF_MAX_LEN];union {__IO uint16_t InfAll;struc ...

  8. TypeScript基础入门之高级类型的可辨识联合(Discriminated Unions)

    2019独角兽企业重金招聘Python工程师标准>>> 转发 TypeScript基础入门之高级类型的可辨识联合(Discriminated Unions) 高级类型 可辨识联合(D ...

  9. 匿名联合(Anonymous unions)

    Anonymous unions-匿名联合 在 C++ 我们可以选择使联合(union)匿名.如果我们将一个 union 包括在一个结构(structure)的定义中,并且不赋予它对象(object) ...

最新文章

  1. 谁再说不熟悉Linux命令,就把这个给他扔过去!
  2. acm数论之欧几里得gcd
  3. 马哥学习笔记——shell变量类型
  4. MySQL的limit用法和分页查询的性能分析及优化
  5. bash特性及bash脚本编程初步
  6. 蓝桥杯第八届省赛JAVA真题----正则问题
  7. Linux QQ 2.0.0 Beta2 发布
  8. 使用redis kv数据库维护kafka主题分区的offset
  9. MyBatis(五)------MyBatis配置
  10. linux中定义用户账户的文件为,Linux中用户和组中认证库和解析库的文件格式以及默认参数定义文件...
  11. CSDN博客代码块语法高亮
  12. [知识点整理]使用论文内容和用户行为对论文推荐进行个性化的重新排序(Personalised Reranking of Paper Recommendations Using Paper Conte)
  13. 蓝牙核心技术概述(一):蓝牙概述
  14. Linux系统替换文件内容
  15. 官方代付系统/支付宝微信代付/企业付款/提现秒到
  16. 【面试题】Redis篇-常见面试题p1
  17. BUU-Crypto-异性相吸
  18. 灰色预测模型介绍及MATLAB代码实现
  19. STM32 电池电压采集之低功耗设计
  20. 35种音乐的分类和解释

热门文章

  1. JS实现鼠标滑过图片的抖动效果
  2. AnyView --哗众取宠的介绍词
  3. dell服务器磁盘的状态变成foreign
  4. 路由器wifi信号测试软件,IT之家实验室:无线路由器2.4GHz和5GHz信号及速率测试...
  5. 爬取东方财富网当日股票交易情况
  6. Vuex中浏览器安装devtools
  7. FFT—快速傅里叶变换算法——matlab(1)
  8. 使用RDO安装havana、icehouse版本的openstack(centos)
  9. 卷积神经网络 - 填充和步幅
  10. 【渝粤教育】国家开放大学2019年春季 1042国际经济法 参考试题