What is this syntax: union{}?

∥☆過路亽.° 提交于 2020-01-06 16:14:29

问题


void display_binary_float(unsigned int ui) {
  union {
    unsigned int ui;
    float f;
  } uif2;
  uif2.ui = ui;
  printf("binary: %08X float: %g\n", uif2.ui, uif2.f);
}

1) What is union? There was no manual entry for it, for some reason. Couldn't find the doc on google.

2) Why is uif2 at the end of the function union? Shouldn't it be something like union uif2 {} or is this a C thing?


回答1:


Wikipedia, it say:

In C and C++, untagged unions are expressed nearly exactly like structures (structs), except that each data member begins at the same location in memory.

I'm sure the documentation for whatever tools you have will tell you all about unions, you just haven't found that section yet.




回答2:


To answer your question (2), uif2 is a variable declared with a type that happens to be a union. The union has no name, so it's called an "anonymous" union. You can do the same with struct, too:

struct {
    int a;
    char *b;
} foo;

This declares a variable called foo which has a type of the given struct.




回答3:


A union allows you to treat a block of memory as different variables/variable types. Each variable shares the same memory, and the total amount of memory used by the union is the amount used by the largest member.

Accessing union members is done exactly as you would access structure members. But while structures contain members that each contain their own memory, members in a union share the same memory and so one or more member may invalid.

Obviously, you can't store multiple values in a union. But, for cases where you want one data type in one case and another data type in another case, it provides a convenient way to store one of those different data types.




回答4:


It's a C keyword, like enum or struct. A union is basically a way to layer several types of variables in the same space. Look it up in any decent C reference.




回答5:


union is like a struct, but with only one field that can be accessed by multiple names. So in your case, uif2.ui and uif2.f both access the same memory location.

http://msdn.microsoft.com/en-us/library/y9zewe0d(v=vs.80).aspx




回答6:


union here means the unsigned int ui and float f are sharing the same memory space.




回答7:


The use of union has been well covered.

The answer for your syntax question is that union { unsigned int ui; float f; } is a type, a union with members ui and f. In an initialization, the values do go after the variable name, but this is a definition rather than an initialization.



来源:https://stackoverflow.com/questions/5225254/what-is-this-syntax-union

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!