C语言 C中的宏常量和常量变量有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3216752/
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
What is the difference between macro constants and constant variables in C?
提问by erkangur
Possible Duplicate:
“static const” vs “#define” in C
可能的重复:C 中的
“静态常量”与“#define”
I started to learn C and couldn't understand clearly the differences between macros and constant variables.
我开始学习C,并不能清楚地理解宏和常量变量之间的区别。
What changes when I write,
我写的时候有什么变化,
#define A 8
and
和
const int A = 8
?
?
回答by Michael
Macros are handled by the pre-processor - the pre-processor does text replacement in your source file, replacing all occurances of 'A' with the literal 8.
宏由预处理器处理 - 预处理器在源文件中进行文本替换,用文字 8 替换所有出现的“A”。
Constants are handled by the compiler. They have the added benefit of type safety.
常量由编译器处理。它们具有类型安全的额外好处。
For the actual compiled code, with any modern compiler, there should be zero performance difference between the two.
对于实际编译的代码,使用任何现代编译器,两者之间的性能差异应该为零。
回答by Lucas Jones
Macro-defined constants are replaced by the preprocessor. Constant 'variables' are managed just like regular variables.
宏定义的常量被预处理器替换。常量“变量”的管理就像常规变量一样。
For example, the following code:
例如,以下代码:
#define A 8
int b = A + 10;
Would appear to the actual compiler as
在实际编译器中会显示为
int b = 8 + 10;
However, this code:
但是,这段代码:
const int A = 8;
int b = A + 10;
Would appear as:
会显示为:
const int A = 8;
int b = A + 10;
:)
:)
In practice, the main thing that changes is scope: constant variables obey the same scoping rules as standard variables in C, meaning that they can be restricted, or possibly redefined, within a specific block, without it leaking out - it's similar to the local vs. global variables situation.
在实践中,变化的主要内容是作用域:常量变量遵循与 C 中标准变量相同的作用域规则,这意味着它们可以在特定块内受到限制或可能重新定义,而不会泄漏 - 它类似于本地vs. 全局变量情况。
回答by swegi
In C, you can write
在C中,你可以写
#define A 8
int arr[A];
but not:
但不是:
const int A = 8;
int arr[A];
if I recall the rules correctly. Note that on C++, both will work.
如果我没记错规则。请注意,在 C++ 上,两者都可以使用。
回答by μBio
For one thing, the first will cause the preprocessor to replace all occurrences of A with 8 before the compiler does anything whereas the second doesn't involve the preprocessor
一方面,第一个将导致预处理器在编译器执行任何操作之前将所有出现的 A 替换为 8,而第二个不涉及预处理器

