5

I define a macro twice as follows:

#define a 2  
#define a 3   

I thought any occurrence of a in the code would be replaced by 2, and when #define a 3 is encountered there are no more as are available in the code to be replaced by 3, so the 2 would take precedence.

But when I executed it a was replaced by 3, why?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Ann562
  • 71
  • 1
  • 2

3 Answers3

11

If you define a macro twice like that, the compiler should at least give you warning, if not an error. It is an error.

§6.10.3/2 : An identifier currently defined as an object-like macro shall not be redefined by another #define preprocessing directive unless the second definition is an object-like macro definition and the two replacement lists are identical.

You can redefine a macro by explicitly removing the previous definition:

#define a 2
/* In this part of the code, a will be replaced with 2 */
...

#undef a
#define a 3
/* From here on, a will be replaced with 3 */
...

Macro replacement happens as the file is read, using the macro definitions active at that point in the file, except inside (most) preprocessing directives.

§6.10/7: The preprocessing tokens within a preprocessing directive are not subject to macro expansion unless otherwise stated.

§6.10.3.5/1: A macro definition lasts (independent of block structure) until a corresponding #undef directive is encountered or (if none is encountered) until the end of the preprocessing translation unit.

Community
  • 1
  • 1
rici
  • 234,347
  • 28
  • 237
  • 341
7

a will not be replaced by 2 in #define a 3 as this is also a pre processor.

After processing #define a 2, the value of a is 2, but it is overwritten by the next statement #define a 3

Sagar Jain
  • 7,475
  • 12
  • 47
  • 83
  • 1
    Yes, you're right, but IMHO you need to expand your answer a bit more to be suitable for this particular question. – Sourav Ghosh Sep 07 '15 at 05:55
5

It's not clear to me what you were expecting to see.

The second line overrides the definition of a from the first line.

Any a encountered after that will be replaced by 3.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • my doubt was does " #define a 2 " will replace " a " by 2 in the line " #define a 3" as well as in other part of the code .Hence the second macro definition will become " #define 2 3" . now "2" is replaced by 3. Is this how it works – Ann562 Sep 07 '15 at 08:31
  • No, the name of a `#define`-d macro is *never* expanded in the definition – Basile Starynkevitch Sep 07 '15 at 10:26