简体   繁体   English

以下代码的输出:联合

[英]Output of the following code.. Union

Can anyone please explain me why would the following code print 20 instead of 10? 谁能解释一下为什么下面的代码显示20而不是10?

Thanks 谢谢

#include<stdio.h>

int main()
{
    union var
    {
        int a, b;
    };
    union var v;
    v.a=10;
    v.b=20;
    printf("%d\n", v.a);
    return 0;
}

By definition of a union : you can't simultaneously use va and vb because both fields share the same address. 根据并集的定义:您不能同时使用vavb因为两个字段共享相同的地址。 To quote the standard : 引用标准:

A union type describes an overlapping nonempty set of member objects , each of which has an optionally specified name and possibly distinct type. 联合类型描述了一组重叠的非空成员对象 ,每个成员对象都有一个可选的指定名称和可能不同的类型。

Here, as soon as you assign to vb , you override va . 在这里,一旦您分配给vb ,您将覆盖va In your case, things don't get ugly because both variables have the same type, but just imagine what if a was a float and b a char for example. 在您的情况下,事情不会变得很难看,因为两个变量具有相同的类型,但仅想象一下如果afloatb是char怎么办。

If your goal is to have var be a compound variable which contains two different int , then you should use struct , not union . 如果您的目标是使var为包含两个不同int的复合变量,则应使用struct而不是union

Unions will be wide enough to store the widest type it contains, and the types will share the same addresses. 联合将足够宽以存储它包含的最广泛的类型,并且这些类型将共享相同的地址。 If you want a and b to be distinct, use a struct . 如果要使ab区分,请使用struct

From the C99 standard, section 6.7.2.1: 根据C99标准的6.7.2.1节:

The size of a union is sufficient to contain the largest of its members. 工会的规模足以容纳其最大的成员。 The value of at most one of the members can be stored in a union object at any time. 成员中最多一个的值可以随时存储在联合对象中。 A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit- field, then to the unit in which it resides), and vice versa. 指向经过适当转换的并集对象的指针指向其每个成员(或者,如果一个成员是一个字段,则指向它所驻留的单元),反之亦然。

From section 6.5.8: 从6.5.8节开始:

All pointers to members of the same union object compare equal. 指向同一联合对象的成员的所有指针比较相等。

Union is a thing that provides access to the same memory with different types modifires. 联合是一种提供对具有不同类型修改的相同内存的访问的东西。 So in your code the first assignement doesn't have much sence, because the second assignement exists. 因此,在您的代码中,第一次分配没有太多意义,因为存在第二次分配。 It impacts the memory in last order, so you get the last assigned value. 它以最后顺序影响内存,因此您将获得最后分配的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM