#defining constants in C++

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

    There is no requirement that T be stored "in memory" in the second case, unless you do something like take the address of it. This is true of all variables.

    The reason the second one is better is that the first will frequently "disappear" in the pre-processor phase so that the compiler phase never sees it (and hence doesn't give it to you in debug information). But that behaviour is not mandated by the standard, rather it's common practice.

    There's little need to use #define statements any more other than for conditional compilation. Single constants can be done with const, multiple related constants can be done with enum and macros can be replaced with inline functions.

提交回复
热议问题