是否有一个宏来定义常量?
宏是一个片段已指定名称的代码。每当使用该名称时,它都会被宏的内容替换。 (不需要内存)
所以,人们用它作为定义常量的方法,而不是语法:const int num = 1;
这是一个好习惯吗?除了 #include
和 #define
之外,宏是否设置为执行其他操作?
Possible Duplicate:
"static const" vs "#define" in c
A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. (No memory required)
So, people use it as a method to define constants instead of the syntax: const int num = 1;
Is this a good habit? Is the MACRO set to do another things additionally to #include
and #define
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除了定义常量之外,还可以出于其他原因使用宏。如今,除非绝对没有其他可用选项,否则宏的使用通常不受欢迎。
调试散布在其中的宏的复杂代码可能会给您带来不止一个头痛。
来自 GCC 文档:
Macros can be used for other reasons than just defining constants. Nowadays, macro usage is generally frowned upon unless there are absolutely no other options available.
Debugging complex code with macros littered throughout can cause you more than one headache.
From GCC docs:
通常出于多种原因首选常量。例如,它们是语言构造(不是预处理器处理的外部值)。此外,它们还包含类型信息,因此它们可以帮助编译器检测编译错误等。在大多数情况下,您可以说它们是等效的,但
const
是“语义上更正确”。Consts are generally preferred for several reasons. For example, they are a lenguage construct (not an external value processed by the preprocessor). Also, they contain type information, so they help the compiler to detect compiling errors, etc. In most cases, you could say they are equivalent, but
const
is "semantically more correct".