In article < .com>
Johan Tibell <> wrote:
[vertically compressed]
>struct exp {
> enum { LIT, VAR } type;
> union { int lit; char *var; } form;
>};
[vs
enum exp_type { LIT, VAR };
struct exp {
enum exp_type type;
union { int lit; char *var; } form;
};
]
>What would be the pros and cons of having it unnamed inside the struct
>versus named outside the struct respectively? I can think of a few:
>
>Pros:
>* Less pollution of the namespace. I currently have two different
>structs so I have to prefix my enum type names with "structname_" (e.g.
>exp_type).
This is a smaller pro than it may look: enumeration members are
in the ordinary namespace, at the same scope as the overall definition
of the structure type, so LIT and VAR can appear anywhere up to
the end of the current scope and must be unique. That is:
struct expression {
enum { LIT, VAR } type;
...
};
struct fuse {
enum { UNLIT, LIT } type;
...
};
is no good -- the two "LIT"s conflict. (In C++ each struct has its
own little sub-namespace, but C is not C++.)
Thus, the only namespace you avoid polluting is the "tag" namespace.
>* Saves me some typing.
Not much, since you can also write:
struct exp {
enum exp_type { LIT, VAR } type;
union { ... } form;
}
>* Avoid repetition of the name "type" in the variable declaration
>inside the struct (e.g. exp_type type).
>
>Cons:
>* Can't create a variable of the enum type since the type can't be
>referred to. (Would it even be possible to refer to the enum type if it
>was named _and_ declared inside the struct?).
Easily fixed by adding an enum tag, as above. Yes, you can refer to
"embedded" types afterward in C:
struct foo {
enum zot { ZOT_A, ZOT_B } zot;
struct bar {
int i;
};
char *p;
};
enum zot zed;
struct bar bar;
(Again, C++ is different -- another reason not to try to compile C
code with a C++ compiler: valid C code is sometimes invalid, but
sometimes valid yet meaning something else, in C++.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it
http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.