#defining constants in C++

后端 未结 7 1056
轮回少年
轮回少年 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:27

    Yes. The biggest reason is that preprocessor definitions do not obey the scoping rules of the language, polluting the global namespace, and worse -- they're even replaced in cases like

    x->sameNameAsPreprocessorToken
    

    Since preprocessor definitions are replaced at the textual level, other normal properties of variables do not apply - you can take the address of an int const, but not of a #define'd constant.

    As noted by others, you also typically lose type safety and debugging ability.

提交回复
热议问题