---
title: "共用体的使用"
author: "cjc"
date: "2009-06-04T16:30:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2009-06-04T16:30:00Z"
id: 402518
url: "https://cjc.iteye.com/blog/402518"
---

&lt;script&gt;function StorePage(){d=document;t=d.selection?(d.selection.type!='None'?d.selection.createRange().text:''):(d.getSelection?d.getSelection():'');void(keyit=window.open('http://www.365key.com/storeit.aspx?t='+escape(d.title)+'&u='+escape(d.location.href)+'&c='+escape(t),'keyit','scrollbars=no,width=475,height=575,left=75,top=20,status=no,resizable=yes'));keyit.focus();}&lt;/script&gt;

**作者：**曾宏安，[华清远见嵌入式学院](http://www.embedu.org/)高级讲师。

在C语言中，不同的成员使用共同的存储区域的数据构造类型称为共用体，简称共用，又称联合体。共用体占用空间的大小取决于类型长度最大的成员。共用体在定义、说明和使用形式上与结构体相似。两者本质上的不同仅在于使用内存的方式上。

定义一个共用体类型的一般形式为：

union 共用体名  
{  
成员表列；  
}；

看一个具体的例子：

union un  
{  
char c；  
short s;  
int i；  
}myun；

共用体变量myun的三个成员：myun.c，myun.s和myun.i共用同一块内存（4个字节大小）。其中， myun.c只使用第一个字节，myun.s使用前两个字节而myun.i使用全部4个字节。如下图所示：

![](http://www.embedu.org/Column/images/Column53-1.jpg)

当我们给其中一个成员赋值时会影响到其他的成员。如 myun.i = 0x11223344，赋值后myun.c的值变成0x44，myun.s的值变成0x3344。

![](http://www.embedu.org/Column/images/Column53-2.jpg)

看一个实际应用的例子，要求计算无符号整型变量x前两个字节和后两个字节相加的和。构造共用体类型如下

union un  
{  
unsigned int i;  
unsigned short s\[2];  
}myun；

myun.i = x;

myun.s\[0]+myun.s\[1]即为要计算的结果。

当然，我们也可以用以下公式直接计算： (x & 0xffff) + ( x &gt;&gt; 16)