开发者

Why are there defined constants and declared constants in CPP?

Why are there two ways to "declare" constants in CPP?

Which is better, or should I write, which of them should I use when?

#define MYCON 100
const int MYCON=100
开发者_JAVA百科


Short rule: For conditional compilation (like different code fragments for DEBUG and RELEASE) use #define. For all other cases use const construction.


Using #define produces a preprocessor symbol: it has no existence at all after preprocessing has occurred and is equivalent to having typed "100" into the file.

Features of preprocessor symbols:

  • You can use them in preprocessor directive like #ifdef
  • It has lexical scope
  • You can not take their address (and therefore cannot use them as arguments where a type* is expected)

Using const type declares a c++ variable.

  • You can not use this thing in preprocessor directives
  • It follows the usual c++ scope rules
  • You can takes it's address

It is widely considered better to use const for "in program" constants and #define only for conditional compilation (which represents a change from the (very!) old days when you could not always rely on c compiler to handle const intelligently and using #define was preferred). If nothing else this gives you better control of the symbol's scope.


In the original version of C, #define was the only method available to declare a constant value. This was done at compile time rather than at run time: The compiler hardcoded the value for each instruction. const is a feature of C++ (later added to C in limited fashion), and in C++ it is recommended that you use const rather than #define. const variables actually exist in memory, and can be initialized at construction during runtime.

#define is, however, still frequently used in C++, mainly for communication with the compiler.

Some examples:

Class header wrappers to prevent multiple class declarations:

#ifdef VAL_H
#define VAL_H

// Define class header

#endif // VAL_H

Conditional Compilation:

// Comment this line to disable debug output
#define DEBUG

// Some code
#ifdef DEBUG
// Only gets compiled if DEBUG is defined.
cerr << "Debug output here" << endl;
#endif
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜