C++ 为什么有人会使用#define 来定义常量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6274008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why would someone use #define to define constants?
提问by
It's simple question but why would someone use #define to define constants?
这是一个简单的问题,但为什么有人会使用 #define 来定义常量?
What's the difference between
有什么区别
#define sum 1
and const int sum = 1;
#define sum 1
和 const int sum = 1;
采纳答案by AnT
#define
has many different applications, but your question seems to be about one specific application: defining named constants.
#define
有许多不同的应用程序,但您的问题似乎是关于一个特定的应用程序:定义命名常量。
In C++ there's rarely a reason to use #define
to define named constants.
在 C++ 中,很少有理由使用#define
定义命名常量。
#define
is normally widely used in C code, since C language is significantly different from C++ when it comes to defining constants. In short, const int
objects are not constantsin C, which means that in C the primary way to define a true constant is to use #define
. (Also, for int
constants one can use enums).
#define
通常广泛用于 C 代码中,因为 C 语言在定义常量时与 C++ 有很大不同。简而言之,const int
对象在 C中不是常量,这意味着在 C 中定义真正常量的主要方法是使用#define
. (另外,对于int
常量,可以使用枚举)。
回答by Alok Save
No one should not!
Actually, One should prefer const int sum = 1;
over #define sum 1
for a number of reasons:
没有人不应该!
其实,每个人都应该喜欢const int sum = 1;
上#define sum 1
了几个原因:
Scope Based Mechanism:
基于范围的机制:
#define
s don't respect scopes so there is no way to create a class scoped namespace. While const variables can be scoped in classes.
#define
s 不尊重作用域,因此无法创建类作用域命名空间。虽然 const 变量可以在类中限定范围。
Avoiding Weird magical numbers during compilation errors:
在编译错误期间避免奇怪的魔法数字:
If you are using #define
those are replaced by the pre-processor at time of precompilation So if you receive an error during compilation, it will be confusing because the error message wont refer the macro name but the value and it will appear a sudden value, and one would waste lot of time tracking it down in code.
如果你使用的#define
那些在预编译的时候被预处理器替换了所以如果你在编译过程中收到错误,那会很混乱,因为错误信息不会引用宏名称而是引用值,并且会出现一个突然的值,并且一个人会浪费大量时间在代码中跟踪它。
Ease of Debugging:
易于调试:
Also for same reasons mentioned in #2, while debugging #define
would provide no help really.
同样出于 #2 中提到的相同原因,而调试#define
实际上不会提供任何帮助。
Thus, to avoid the above situations const
will be a better choice.
因此,避免上述情况const
将是一个更好的选择。
回答by Sven
For the example that you just gave, I would normally use a const. Except of course, the #define can be used for conditional compilation elsewhere:
对于您刚刚给出的示例,我通常会使用 const。当然,#define 可用于其他地方的条件编译:
#if SOME_DEFINE == 1
// Conditional code
#endif
This is something you can't do with a const. If you don't need the value to be accessible from the preprocessor, I'd say use a const unless there's some reason why that's not possible. There's some stuff on this in the C++ FAQ lite, where they rightly point out that just because the preprocessor is "evil", it doesn't mean you'll never need it.
这是你不能用 const 做的事情。如果您不需要从预处理器访问该值,我会说使用 const 除非有某种原因这是不可能的。在C++ FAQ lite 中有一些关于这个的东西,他们正确地指出,仅仅因为预处理器是“邪恶的”,并不意味着你永远不需要它。
回答by Karl Knechtel
#define
is necessary to make things like inclusion guards work, because C++ doesn't have a realmodule import system.
#define
使包含守卫之类的东西工作是必要的,因为 C++ 没有真正的模块导入系统。
#define
causes a literal textual substitution. The preprocessor understands how to tokenize source code, but doesn't have any idea what any of it actually means. When you write #define sum 1
, the preprocessor goes over your code and looks for every instance of the token sum
and replaces it with the token 1
.
#define
导致字面文本替换。预处理器了解如何标记源代码,但不知道它的实际含义。当您编写时#define sum 1
,预处理器会检查您的代码并查找令牌的每个实例sum
并将其替换为令牌1
。
This has a variety of limitations: #define sq(x) x * x
will not work right if you use it like sq(3+3)
; and using #define
for a constant does not respect scope in any way, nor does it associate any kind of type with the constant. However, #define
can be used (especially in combination with some other special stuff like the #
and ##
preprocessor operators) to do some magic that is otherwise not possible (except by manually doing what the preprocessor does).
这有多种限制:#define sq(x) x * x
如果您使用它,将无法正常工作sq(3+3)
;并且使用#define
for 常量不以任何方式尊重范围,也不会将任何类型的类型与常量相关联。但是,#define
可以使用(特别是与其他一些特殊的东西,如 the#
和##
preprocessor 运算符结合使用)来做一些否则不可能的魔术(除非手动执行预处理器所做的工作)。
回答by malkia
Always try to use "const int", rather than #define.
总是尝试使用“const int”,而不是#define。
Use #define, only when your preprocessor code might be read by another tool, and it's easier for it to go with the preprocessor, rather than to parse the language.
仅当您的预处理器代码可能被其他工具读取时才使用 #define,并且它更容易与预处理器一起使用,而不是解析语言。
Also it's the only way to define something to be checked later by #if/#else/#endif
它也是定义稍后由 #if/#else/#endif 检查的内容的唯一方法
回答by John Joe
From Introduction to programming with C++which was written by Daniel Liang stated that:
从介绍与C ++编程写由梁丹尼说:
When you define a constant using
#define
directive, the constant is not stored in memory.The constant will be replaced with a value by compiler. When you declare constant usingconst
keyword, the constant is stored in memory just like variable.
当您使用
#define
指令定义常量时,该常量不会存储在内存中。该常量将被编译器替换为一个值。当您使用const
关键字声明常量时,常量就像变量一样存储在内存中。
If constant need to be used in multiple programs, use #define
to define it in header fileso it can be included in other program. If constant used only in one program, using const
to declare is more efficient.
如果常量需要在多个程序中使用,则使用#define
在头文件中定义它,以便它可以包含在其他程序中。如果常量只在一个程序中使用,使用const
to declare 效率更高。
回答by iammilind
In simple words
简单来说
#define sum 1 /*is pre processed*/
Which means, that sum
doesn't exist after the preprocessing stage is finished.
这意味着,sum
在预处理阶段完成后就不存在了。
const int sum = 1; /*is compiled/linked*/
Which means sum
exists till the executable is made out of your program.
这意味着sum
存在直到可执行文件由您的程序制成。
回答by robbrit
const int
is just an int that can't change. #define
is a directive to the C preprocessor, which is much more than just for defining constants.
const int
只是一个无法改变的 int 。#define
是 C 预处理器的指令,它不仅仅是用于定义常量。
See here for more details: http://en.wikipedia.org/wiki/C_preprocessor
有关更多详细信息,请参见此处:http: //en.wikipedia.org/wiki/C_preprocessor
回答by Synxmax
The first is a preprocessor directive, before the compiler compiles your code, it will go through and replace sum with 1. The second declares a variable in memory to hold that quantity. I'm sure it can be argued as to which is best, but the "const int" is probably more common in C++ (when it comes to numeric constants).
第一个是预处理器指令,在编译器编译您的代码之前,它会遍历并将 sum 替换为 1。第二个在内存中声明一个变量来保存该数量。我确信可以争论哪个是最好的,但是“const int”在 C++ 中可能更常见(当涉及到数字常量时)。
http://www.geekpedia.com/KB114_What-is-the-difference-between-sharpdefine-and-const.html
http://www.geekpedia.com/KB114_What-is-the-difference-between-sharpdefine-and-const.html