hello
hello

Reputation: 1228

Difference between using define and variable

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?

Upvotes: 1

Views: 91

Answers (3)

Samer
Samer

Reputation: 1980

#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

Upvotes: 2

Quentin
Quentin

Reputation: 63124

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;

Upvotes: 3

Kerrek SB
Kerrek SB

Reputation: 477020

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

Upvotes: 3

Related Questions