Hello all.
Reading about unions, today. given a general format for their declaration:
1 2 3 4 5 6 7
|
union union_name {
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
.
.
} object_names;
|
Ok. Cool. Looks like a struct (in terms of format, I fully understand that its functionality is different). After the scope delimiters, before the semicolon, there is a union object initializer list. I take it at face value that "union_name" is the name of the union, and that object_names represent an instance or instances of said union.
Then a concrete example:
1 2 3 4 5
|
union mytypes_t {
char c;
int i;
float f;
} mytypes;
|
Makes sense to me.
Begin reading about anonymous unions. Not sure what their practical use is outside of typing less. I can access union members without the union name, apparently.
I read this:
In C++ we have the option to declare anonymous unions. If we declare a union without any name, the union will be anonymous and we will be able to access its members directly by their member names. For example, look at the difference between these two structure declarations:
|
Then I get given these examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
//structure with regular union:
struct {
char title[50];
char author[50];
union {
float dollars;
int yen;
} price;
} book;
//structure with anonymous union
struct {
char title[50];
char author[50];
union {
float dollars;
int yen;
};
} book;
|
I can't help but notice that what is referred to in the above, quoted paragraph as a "union without any name" ends up being without a union name in both the example labeled "regular" as well as the example labeled "anonymous."
Instead, one just has a named
object of the union (but no union name like mytypes_t from the first concrete example or union_name from the general format example).
Is the object name the same thing as the union name? That's what I'm telling myself thus far, since in the concrete example with mytypes_t, we access members without the "_t" in the union name.
1 2 3 4
|
//like this:
mytypes.c
//instead of this:
mytypes_t.c
|
if I am correct in what I am telling myself, then what's up with the _t? Is it pure convention, or does it achieve something?
And why isn't it also in the example with price? Like this:
1 2 3 4 5 6 7 8 9
|
//structure with regular union:
struct {
char title[50];
char author[50];
union price_t{
float dollars;
int yen;
} price;
} book;
|