开发者

Priority of #define vs. const declaration

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开发者_StackOverflow社区 FOO 23

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


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.

  • C++ - enum vs. const vs. #define
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜