#defining constants in C++

后端 未结 7 1073
轮回少年
轮回少年 2021-02-01 03:50

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

#define T 100

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

const int T =         


        
7条回答
  •  甜味超标
    2021-02-01 04:28

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

    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.

    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.

提交回复
热议问题