为什么我们需要C3工会? [英] Why do we need C Unions?

查看:126
本文介绍了为什么我们需要C3工会?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当工会应该被使用?我们为什么需要他们?

When should unions be used? Why do we need them?

推荐答案

联盟经常被用来整数的二进制重新presentations之间进行转换,浮

Unions are often used to convert between the binary representations of integers and floats:

union
{
  int i;
  float f;
} u;

// Convert floating-point bits to integer:
u.f = 3.14159f;
printf("As integer: %08x\n", u.i);

尽管这是根据C标准(你只应该读这是最近写的字段),它会在一个定义良好的方式行事在几乎任何编译器。技术上未定义的行为

Although this is technically undefined behavior according to the C standard (you're only supposed to read the field which was most recently written), it will act in a well-defined manner in virtually any compiler.

工会有时也被用来实现伪多态性C,给人一种结构的一些标签,表明它包含什么类型的对象,然后unioning可能的类型在一起:

Unions are also sometimes used to implement pseudo-polymorphism in C, by giving a structure some tag indicating what type of object it contains, and then unioning the possible types together:

enum Type { INTS, FLOATS, DOUBLE };
struct S
{
  Type s_type;
  union
  {
    int s_ints[2];
    float s_floats[2];
    double s_double;
  };
};

void do_something(struct S *s)
{
  switch(s->s_type)
  {
    case INTS:  // do something with s->s_ints
      break;

    case FLOATS:  // do something with s->s_floats
      break;

    case DOUBLE:  // do something with s->s_double
      break;
  }
}

这使得中的struct的大小来只有12字节,而不是28。

This allows the size of struct S to be only 12 bytes, instead of 28.

这篇关于为什么我们需要C3工会?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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