1

If I have the code below:

#define POUND_PER_DOLLAR  73
int nPound = 4 * POUND_PER_DOLLAR;

AND

int POUND_PER_DOLLAR = 122;
int nPound = 4 * POUND_PER_DOLLAR;

Are there instances where usage of one is more suited than the other?

hello
  • 1,168
  • 4
  • 24
  • 59

3 Answers3

3

If you need the address, you need a variable:

void foo(int *);

foo(&POUND_PER_DOLLAR);         // must be an lvalue

If you need a constant expression, a macro (or at least a constant) will work:

char array[POUND_PER_DOLLAR];   // must be a constant expression

However, the most appropriate construction is probably a constant:

const int kPoundPerDollar = 73;
int nPound = 4 * kPoundPerDollar;

void bar(const int *);
bar(&kPoundPerDollar);                 // works
char c[kPoundPerDollar];               // also works

template <const int * P> struct X {};
X<&kPoundPerDollar> x;                 // also works
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
3

Neither. The #define is not type-safe, the int is non-const. This is the constant you're looking for :

int const POUND_PER_DOLLAR = 122;
Quentin
  • 62,093
  • 7
  • 131
  • 191
  • except it looks fugly in ALL_CAPS and there's no good reason for that. [Stop the constant SHOUTING](http://accu.org/index.php/journals/1923). – Jonathan Wakely Aug 01 '14 at 13:58
2
#define identifier replacement

When the preprocessor encounters this directive, it replaces any occurrence of identifier in the rest of the code by replacement. This replacement can be an expression, a statement, a block or simply anything. The preprocessor does not understand C++ proper, it simply replaces any occurrence of identifier by replacement.

Disadvantages of using #define: method,

  1. the preprocessor does not understand any c++, it only replaces it, so you are taking your own risk
  2. It makes it harder for debugging, if you are using a debugger and you want to check the values of your variables
  3. You Have to be careful of redefinition of your macro
Samer
  • 1,923
  • 3
  • 34
  • 54