Reputation: 3701
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?
Upvotes: 0
Views: 537
Reputation: 361352
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.
Upvotes: 8