c++ - #define 与 const 声明的优先级

标签 c++ variables constants c-preprocessor overwrite

#define 能否“覆盖”const 变量,反之亦然?还是会导致编译错误?

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

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

在 42 或 23 这两种情况下,FOO 的值是多少?

最佳答案

第一个会给出编译错误。从定义的角度来看,宏是可见的。

也就是说,第一个相当于:

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

第二个是这样的:

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

因为宏是哑的,在 C++ 中 constenum 优于宏。在这里查看我的回答,我在其中解释了为什么宏不好,constenum 是更好的选择。

关于c++ - #define 与 const 声明的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7370535/

相关文章:

php - 在 PHP 中定义类常量

c++ - c2664 无法将参数 2 从 'std::string' 转换为 'const void *'

angular - 如何从父 Angular 2 获取子变量

.NET const 影响编译的程序集大小

vb6 - 我应该如何使多个项目之间的常量可见?

c - C 中的变量定义忽略

c++ - 这个赋值运算符后面的 & 是什么意思?

c++ - 将内存中的16位转换为std::string

c++ - 如何用qdbusxml2cpp生成同步接口(interface)类?

regex - 将部分匹配模式保存到变量