blockstack said:
I recently noticed (I'm new to the language) that when using a union
type as a component of a structure, you don't need a union-tag.
struct foo
{
char *ptr;
union
{
int i;
float f;
char c;
};
};
I have never read that a union type reference is optional in any
case.
Is this specific to the compiler, or part of the standard?
A union does not need to have a union tag, and a struct
does not need to have a struct tag. But I think you may be
mixing up the terminology!
- A "struct tag" is an identifier that can be combined
with the keyword `struct' to form a name for a specific
struct type. In your example, `foo' is a struct tag
and `struct foo' is the name of the type. If the `foo'
were absent, the struct would have no tag and there
would be no way to write a name for its type elsewhere
in the program.
- Similarly, a "union tag" is an identifier that can be
combined with the keyword `union' to form a name for a
specific union type. In your example, the union has no
tag and there is no way to write the name of the union's
type. If the identifier `bar' appeared right after the
`union' keyword, `bar' would be the union tag and
`union bar' would be the name of the type.
- Almost every element contained in a struct or union (the
lone exception is not important here) must have an element
name. In your example, `i', `f', and `c' are the names
of the elements of the union. `ptr' is the name of one
element of the struct, but the other element (the union)
has no name. This is a compile-time error for which the
compiler is required to produce a diagnostic message.
So, why do you get no error message? Probably because you
are not using a C compiler, but a C-with-extras compiler that
accepts a C-like language that isn't really C. The gcc compiler
is like that in its default mode of operation; command-line flags
like `-ansi -pedantic' can make it conform more strictly to the
actual definition of C.