Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: enums in structs Date: Wed, 14 Mar 2018 17:57:07 -0700 Organization: None to speak of Lines: 53 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: reader02.eternal-september.org; posting-host="4062d3804107f3b0a8439aa53526a52c"; logging-data="8940"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18p838D7oeTD7OviIvZVQtm" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:DwY6D2+Vj1/9VTYrUot4PfEbxMM= sha1:ycBaRwvS4AjkR5K9KFvr5TTfR3c= Xref: csiph.com comp.lang.c:127834 bartc writes: > I thought I knew most of the C quirks, but here's another one which I > don't think I've seen before (perhaps with enum tags, not names): > > typedef struct {enum {red,green,blue} x;} S; The typedef is irrelevant. This: struct S { enum { red, green, blue } x; }; illustrates the same thing. > Despite being declared inside the {...} of the struct, the scope of red, > green and blue belong to the outer scope (the one containing the typedef). Not all curly braces define scopes. Take a look at N1570 6.2.1 "Scopes of identifiers". There's no such thing as "struct scope". The only scopes are: - Function scope (applies only to labels) - File scope - Block scope (refers to a block / compound statement) - Function prototype scope (not often used) Note that the member name "x" also has a wider scope than the struct. But member names always have to be prefixed with "s." or "p->". > Which also means that: > > typedef struct {enum {red,green,blue} x;} S; > typedef struct {enum {red,green,blue} x;} T; > > won't work, as the names will clash. Right. If "red", "green", and "blue" had scopes restricted to the struct definition, you wouldn't be able to refer to their names outside the struct definition. C has no mechanism for prefixing an enumeration constant with the name of a type. (You'd usually want to define the enum type separately -- or at least I would.) [...] -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"