0

In the below piece of code :

union
{
float dollars;
int yens;
}price;

Is price an instance of an anonymous union or is it the name of the union itself. It looks to me like an instance but the author of the code says it's the name of the union.

Now, the second question - Suppose if this union is embedded in a structure like below:

struct
{
char title[50];
char author[50];
union
{
float dollars;
int yens;
}price;
}book1;

Would an access book1.dollars be valid?

sjsam
  • 21,411
  • 5
  • 55
  • 102

1 Answers1

2

1) It is an instance of an anonymous union indeed, the author was wrong. If you prepend the union with a typedef keyword like

typedef union
{
   float dollars;
   int yens;
} price;

, then price will be a typename referring to the union.

2) Nope, book1.price.dollars you want to use instead.

UPDATE: An union type can be declared in the following way either:

union price
{
   float dollars;
   int yens;
}; // here you see, there is no instance.

If there was an identifier between the closing brace and the semicolon, that would be the name of the instance.

Géza Török
  • 1,397
  • 7
  • 15
  • But what if I wish too override the **price** instance? – sjsam Mar 25 '15 at 08:09
  • I don't seem to understand your question. How to override an _instance_? – Géza Török Mar 25 '15 at 08:10
  • so in case of 1, without typedef price is a variable already ? I did not notice the missing typedef before ;-), do you happen to know why this would be usefull ? – Philip Stuyck Mar 25 '15 at 08:11
  • @Géza Török : say, what if I don't want to use this instance? – sjsam Mar 25 '15 at 08:12
  • @PhilipStuyck Yes it is a variable already :) I could explain some use cases where it is very handy but a comment is not the place where I can do so, it's a bit longer, needs examples, etc. Create a question and i'll be there :) – Géza Török Mar 25 '15 at 08:15
  • @sjsam there are two ways to declare a type without specifying an instance initially. The first is the one I mentioned in my answer, with `typedef`, the second one is the way how you declare classes. Please have a look @ my update in a minute :) – Géza Török Mar 25 '15 at 08:17
  • http://stackoverflow.com/questions/29250665/what-is-the-use-case-for-an-anonymous-union-type is my question ;-) – Philip Stuyck Mar 25 '15 at 08:27
  • @GézaTörök : Declaring classes without an object - the method you pointed out by your edit - is obvious. But, to put it this way, suppose we don't put `typedef` in front, thus creating anonymous union, it sounds strange to create a instance of such a union. Aint it? – sjsam Mar 25 '15 at 08:28
  • No it isn't. In fact it is very useful, and if beloved SO didn't close the question of @PhilipStuyck, I would have provided a detailed explanation on this... :( – Géza Török Mar 25 '15 at 08:30
  • I voted to reopen, they link to an explanation of union with typedef. – Philip Stuyck Mar 25 '15 at 08:31