gpt4 book ai didi

c++ - C++中的宏和常量有什么区别?

转载 作者:IT老高 更新时间:2023-10-28 21:55:05 25 4
gpt4 key购买 nike

我在一次技术面试中被问到这个问题:

What is the difference between a const and a macro in C++?

我的回答是宏是一个预处理器指令,如果使用宏可能很难调试应用程序,因为它在编译之前被常量表达式替换,而 const 可以类型标识符,易于调试。

谁能指出任何其他区别,哪个应该是首选?

编辑:

来自 IBM 的 C++ 文档:

The following are some differences between #define and the const type qualifier:

  1. The #define directive can be used to create a name for a numerical, character, or string constant, whereas a const object of any type can be declared.

  2. A const object is subject to the scoping rules for variables, whereas a constant created using #define is not. Unlike a const object, the value of a macro does not appear in the intermediate source code used by the compiler because they are expanded inline. The inline expansion makes the macro value unavailable to the debugger.

  3. A macro can be used in a constant expression, such as an array bound, whereas a const object cannot. (I think we surely need to use macro to define array_size.

  4. The compiler does not type-check a macro, including macro arguments.

最佳答案

宏和常量并不是一回事,有时每个都适合具体情况,而您的回答只是触及了差异的表面。此外,C++ 有两种不同的常量。

const 限定符定义的常量最好被视为一个不可修改的变量。它具有变量的所有属性:它有一个类型,它有一个大小,它有链接,你可以获取它的地址。 (编译器可能会优化掉其中的一些属性,如果它可以摆脱它:例如,从未使用过地址的常量可能不会被发送到可执行镜像中。但这只是由于 as-if 规则的恩典。 ) 唯一不能对 const 数据做的事情就是改变它的值。用 enum 定义的常量有点不同。它有一个类型和一个大小,但它没有链接,你不能取它的地址,它的类型是唯一的。这两个都是在翻译阶段 7 处理的,所以它们只能是左值或右值。 (我很抱歉前一句中的行话,但我不得不写几段。)

宏的约束要少得多:它可以扩展到任何标记序列,只要整个程序仍然是一个格式良好的程序。它没有任何变量的属性。将 sizeof& 应用于宏可能会或可能不会做一些有用的事情,这取决于宏扩展的内容。宏有时被定义为扩展为数字文字,并且这些宏有时被认为为常量,但它们不是:“编译器正确”(即翻译阶段 7)将它们视为 < em>数字字面量.

现在通常认为是一种很好的做法,当常量可以使用时不要使用宏。宏不遵守与所有其他标识符相同的范围规则,这可能会造成混淆,如果您使用常量,您会为翻译阶段 7 提供更多信息,从而也提供给调试器。但是,宏允许您做任何其他方式无法完成的事情,如果您需要做其中一件事情,您应该毫不犹豫地使用它们。 (从这个意义上说,正在发挥作用的宏通常只是扩展为数字文字,尽管我不会说永远不会。)

编辑:这是一个宏做一些有趣事情的例子。它绝不是一个常数,形状或形式。很可能有一种方法可以在没有宏的情况下获得相同的效果(如果你知道一个不涉及字符串流的方法,我很想知道它!)但我认为它很好地说明了功能和宏的危险(对于后者,请考虑如果在一个非常特定的上下文之外使用它会做什么......)

static double elapsed()
{ ... }
#define ELAPSED '[' << std::fixed << std::setprecision(2) << elapsed() << "] "

// usage:
for (vector<string>::iterator f = files.begin(); f != files.end(); f++) {
cout << ELAPSED << "reading file: " << *f << '\n';
process_file(*f);
}

关于c++ - C++中的宏和常量有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6393776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com