什么是用C工会背后的意义呢? [英] What is the point behind unions in C?

查看:98
本文介绍了什么是用C工会背后的意义呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经历O'Reilly的实用C语言程序设计的书,看过的K&放大器; R书中对C语言编程,和我真的有麻烦抓工会背后的概念。

I'm going through O'Reilly's Practical C Programming book, and having read the K&R book on the C programming language, and I am really having trouble grasping the concept behind unions.

他们采取使它们最大的数据类型的大小...和最近分配的一个覆盖休息......但需要为什么不使用/空闲内存?

They take the size of the largest data type that makes them up...and the most recently assigned one overwrites the rest...but why not just use / free memory as needed?

这本书中提到,它在通信,你需要设置相同大小的标志使用;并在谷歌搜索网站,它可以消除奇数大小的内存块......但它是任何使用在一个现代的,非嵌入式内存空间?

The book mentions that it's used in communication, where you need to set flags of the same size; and on a googled website, that it can eliminate odd-sized memory chunks...but is it of any use in a modern, non-embedded memory space?

有什么狡猾的你可以用它和CPU寄存器值吗?这纯粹是一个从节目的早期时代,抱过来?还是它,就像臭名昭著的goto,仍然有一些强大的应用(可能在狭小的存储空间),使得它值得保留在吗?

Is there something crafty you can do with it and CPU registers? Is it simply a hold over from an earlier era of programming? Or does it, like the infamous goto, still have some powerful use (possibly in tight memory spaces) that makes it worth keeping around?

推荐答案

好了,你几乎回答了你的问题:内存。
早在天记忆是相当低的,甚至节省几个字节一直是很有用的。

Well, you almost answered your question: Memory. Back in the days memory was rather low, and even saving a few kbytes has been useful.

不过,即使今天有场景中的工会将是有益的。例如,如果你想实现某种变量数据类型。要做到这一点,最好的方法是使用一个联盟。

But even today there are scenarios where unions would be useful. For example, if you'd like to implement some kind of variant datatype. The best way to do this is using a union.

这听起来并不像很多,但让我们只是假设你想用一个变量或者存储4个字符的字符串(如一个ID)或4字节数(可能是一些散或甚至只是一个数字)。

This doesn't sound like much, but let's just assume you want to use a variable either storing a 4 character string (like an ID) or a 4 byte number (which could be some hash or indeed just a number).

如果您使用的是经典的结构,这将是8个字节长(至少,如果你运气不好有填充字节以及)。使用联盟它只有4个字节。所以你节省50%的内存,这是不是有很多的一个实例,但是想象一下,有这些百万。

If you use a classic struct, this would be 8 bytes long (at least, if you're unlucky there are filling bytes as well). Using an union it's only 4 bytes. So you're saving 50% memory, which isn't a lot for one instance, but imagine having a million of these.

虽然可以通过铸造或继承工会达成类似的事情仍然要做到这一点最简单的方法。

While you can achieve similar things by casting or subclassing a union is still the easiest way to do this.

这篇关于什么是用C工会背后的意义呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆