This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: enum and macro collision
- From: David Brown <david at westcontrol dot com>
- To: vijay nag <vijunag at gmail dot com>, Jonathan Wakely <jwakely dot gcc at gmail dot com>
- Cc: "gcc-help at gcc dot gnu dot org" <gcc-help at gcc dot gnu dot org>
- Date: Tue, 17 Jan 2017 16:05:41 +0100
- Subject: Re: enum and macro collision
- Authentication-results: sourceware.org; auth=none
- References: <CAKhyrx8qVfNmyHPEb1RGH=x=japHc__HQPFG3yoiu7N_6tVP5Q@mail.gmail.com> <CAH6eHdTe=83orEkMQP46W1rfvDiy0O2efcDPwgj0+rwb=nQFfg@mail.gmail.com> <CAKhyrx9PHpQ811+91V8kqZbAqvvj44rX0jO_SNDNaV9jfrKVKg@mail.gmail.com>
On 17/01/17 12:12, vijay nag wrote:
> On Tue, Jan 17, 2017 at 4:36 PM, Jonathan Wakely <jwakely.gcc@gmail.com> wrote:
>> On 17 January 2017 at 11:03, vijay nag wrote:
>>> Hello Gcc,
>>>
>>> I came across this nasty C code of an enumerator and a macro having
>>> the same name. Although this is a buggy code, I found it surprising
>>> that GCC compiles in one of the cases(snippet 1) while in the other
>>> compiler flags an error(snippet 2). Would be interested to know why
>>> the order of definitions/declarations matter and what C standards the
>>> compiler is adhering to ?
>>
>> Just look at the preprocessed code, it should be obvious.
>>
>> Macros aren't defined until they're defined.
>>
>> When the macro is defined after the enumerator it can't change it and
>> you get a valid enumerator definition, FOO = 1.
>>
>> When the macro is defined earlier it produces an invalid enumerator,
>> 0xDEADBEEF = 1
>>
>> What isn't clear?
>
> Thanks for the reply, it is clear now. So, can enum have same name as
> that of a macro and Is it allowed in C ?
>
You can have macros with names that clash with all sorts of things in C,
including identifiers and keywords. Usually it's a bad idea, but it's
up to you. Macros are just textual substitution - after the #define FOO
line, any time the token FOO is found the compiler (pre-processor)
pastes in the definition of FOO. And previous uses of the word FOO are
lost (unless you get them via other macros).