Difference between Enum and Define Statements(枚举和定义语句之间的区别)
问题描述
在 C/C++ 中使用 define 语句和 enum 语句有什么区别(在 C 或 C++ 中使用它们时有什么区别)?
What's the difference between using a define statement and an enum statement in C/C++ (and is there any difference when using them with either C or C++)?
例如,什么时候应该使用
For example, when should one use
enum {BUFFER = 1234};
结束
#define BUFFER 1234
推荐答案
enum
定义了一个语法元素.
enum
defines a syntactical element.
#define
是一个预处理器指令,在编译器看到代码之前执行,因此不是 C 本身的语言元素.
#define
is a pre-preprocessor directive, executed before the compiler sees the code, and therefore is not a language element of C itself.
通常首选枚举,因为它们是类型安全的并且更容易被发现.定义更难定位并且可能具有复杂的行为,例如一段代码可以重新定义由另一段代码创建的 #define
.这可能很难追踪.
Generally enums are preferred as they are type-safe and more easily discoverable. Defines are harder to locate and can have complex behavior, for example one piece of code can redefine a #define
made by another. This can be hard to track down.
这篇关于枚举和定义语句之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:枚举和定义语句之间的区别


基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01