Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

c - Assigning two values with an union variable

The variable a is assigned by value 10 and the variable b is assigned by 20 with the union variable v. Then it gives the output of a is 20 instead of 10. I don't get it.

#include<stdio.h>  
int main()  
{
   union var
   {
       int a, b;
   };
   union var v;
   v.a=10;
   v.b=20;
   printf("%d
", v.a);
   return 0;
}  

I executed the program and I got 20 as output.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

union overlays all the listed members on top of each other (although some may extend farther than the overlapping initial sections), so assigning to either .a or .b is writing over the same part of memory. With that in mind, the output should make sense.

You probably were thinking of struct's behavior if you were expecting an output of 10.

In really twisted scenarios, it's possible to have parts of different values stored in a union simultaneously, but generally the partially overwritten values will be assumed corrupt. For example, this:

union {
    char a;
    struct { char ba; char bb; } b;
} s;

can store s.a and s.b.bb at the same time, but since s.a overlaps s.b.ba, assigning to s.a stomps on s.b.ba, and by implication all of s.b is no longer trustworthy.

Often unions intended to store different types will be embedded in a struct whose first member records which union member is in use:

struct {
    int type;
    union {
       char ch;
       int n;
    } datum;
} atom;

Here, type probably would contain an enumerated value to indicate whether datum.ch or datum.n was in use in the atom.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...