Is it considered bad programming practice to #define constants in C++?
Yes, because all macros (which are what #define
s define) are in a single namespace and they take effect everywhere. Variables, including const
-qualified variables, can be encapsulated in classes and namespaces.
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.
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…