0

can a #define "overwrite" a const variable or vice versa? Or will it lead to a compiler error?

//ONE
#define FOO 23
const int FOO = 42;

//TWO
const int FOO = 42;
#define FOO 23

What value will FOO have in both cases, 42 or 23?

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
blubberbernd
  • 3,491
  • 7
  • 33
  • 45

1 Answers1

8

First one will give compilation error. Macros are visible from the point of their definition.

That is, first one is equivalent to:

//ONE
#define FOO 23
const int 23= 42; //which would cause compilation error

And second one is this:

//TWO
const int FOO = 42;
#define FOO 23 //if you use FOO AFTER this line, it will be replaced by 23

Since macros are dumb, in C++ const and enum are preferred over macros. See my answer here in which I explained why macros are bad, and const and enum are better choices.

Community
  • 1
  • 1
Nawaz
  • 341,464
  • 111
  • 648
  • 831