#定义C ++中的常量

问题描述:

在各种C代码中,我看到了这样定义的常量:

In various C code, I see constants defined like this:

#define T 100

在C ++示例中,几乎总是这样:

Whereas in C++ examples, it is almost always:

const int T = 100;

据我了解,在第一种情况下,预处理器会将T的每个实例替换为100.在第二个示例中,T实际上存储在内存中.

It is my understanding that in the first case, the preprocessor will replace every instance of T with 100. In the second example, T is actually stored in memory.

在C ++中#define常量是否被认为是不好的编程习惯?

Is it considered bad programming practice to #define constants in C++?

在C ++中#define常量是否被认为是不好的编程习惯?

Is it considered bad programming practice to #define constants in C++?

是的,因为所有宏(它们是 #define 定义的)都在单个命名空间中,并且它们在任何地方都有效.变量(包括 const 限定的变量)可以封装在类和名称空间中.

Yes, because all macros (which are what #defines define) are in a single namespace and they take effect everywhere. Variables, including const-qualified variables, can be encapsulated in classes and namespaces.

在C语言中使用宏,因为在C语言中,限定 const 的变量实际上不是常量,而只是一个不能修改的变量.限定为 const 的变量不能出现在常量表达式中,因此,例如,它不能用作数组大小.

Macros are used in C because in C, a const-qualified variable is not actually a constant, it is just a variable that cannot be modified. A const-qualified variable cannot appear in a constant expression, so it can't be used as an array size, for example.

在C ++中,使用常量表达式(例如 const int x = 5 * 2; )初始化的 const 合格对象是 常量,并且可以在常量表达式中使用它,因此您可以并且应该使用它们.

In C++, a const-qualified object that is initialized with a constant expression (like const int x = 5 * 2;) is a constant and can be used in a constant expression, so you can and should use them.