Unions

  1.  union WeightType
  2. {
  3.     long wtInOunces;
  4.     int wtInPounds;
  5.     float wtInTons;
  6. };
  7. WeightType weight;

    At run time, the memory space allocated to the variable weight does not include room for three distinct components. Instead, weight can contain only one of the following: either a long value or an int value or a float value. The assumption is that the program will never need a weight in ounces, a wight in pounds, and a wight in tons simultaneously while executing. The purpose of a union is to conserve memory by forcing several values to use the same memory space, one at a time. The following code shows how the weight variable might be used.

  1. weight.wtInTons = 8.43;
  2.  .
  3.  .
  4. //Weight in tons is no longer needed. Reuse the memory spaces 
  5. weight.wtInPounds = 35;
  6.  . 
  7.  .

 

After the last assignment statement, the previous float value 8.43 is gone, replaced by the int values 35.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值