简体   繁体   中英

Output of the following code.. Union

Can anyone please explain me why would the following code print 20 instead of 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. 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 . 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.

If your goal is to have var be a compound variable which contains two different int , then you should use struct , not 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 .

From the C99 standard, section 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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