Why are constants and declared constants defined in CPP?

Why are there two ways to "declare" constants in CPP?
Which is better, or should I write which one should I use, when?

#define MYCON 100
const int MYCON=100

      

+2


a source to share


3 answers


A short rule of thumb: for conditional compilation (e.g. for different code snippets for DEBUG and RELEASE) use #define

. For all other cases, use the construct const

.



+8


a source


Usage #define

creates a preprocessor symbol: it doesn't exist at all after preprocessing and is equivalent to typing "100" into the file.

Features of preprocessor symbols:

  • You can use them in a preprocessor directive like #ifdef

  • It has a lexical area.
  • You cannot take their address (and therefore cannot use them as arguments where expected type*

    )


Usage const type

declares a C ++ variable.

  • You cannot use this thing in preprocessor directives.
  • It follows the usual C ++ scope rules
  • You can take his address

It is generally accepted that it is better to use const

for constants "in program" and #define

only for conditional compilation (which is a change from the (very!) Old days when you could not always rely on the c handle compiler const

reasonably and the use #define

was preferred). If nothing else gives you better control over the character area.

+1


a source


In the original version of C, this #define

was the only method to declare a constant value. This was done at compile time, not at run time: the compiler programmed a value for each command. const

is a C ++ function (later added to C in a limited way), and in C ++ it is recommended to use const rather than #define. const

actually exist in memory and can be initialized when built at runtime.

#define

however, is still often used in C ++, mainly for compiler communication.

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


a source







All Articles