Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are there defined constants and declared constants in CPP?

Tags:

c++

constants

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
like image 795
Itay Moav -Malimovka Avatar asked Nov 23 '25 14:11

Itay Moav -Malimovka


2 Answers

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

like image 90
Oleg Avatar answered Nov 26 '25 03:11

Oleg


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.

like image 29
dmckee --- ex-moderator kitten Avatar answered Nov 26 '25 04:11

dmckee --- ex-moderator kitten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!